在前述的新增登入功能程序中,應用程式只會在用戶端驗證使用者;在這種情況下,您只能在使用者積極使用應用程式時存取 Google API。如果您希望伺服器能夠代表使用者 (可能在使用者離線時) 發出 Google API 呼叫,則伺服器需要存取權存取金。
事前準備
- 設定專案
- 在應用程式中新增 Google 登入按鈕
- 為後端伺服器建立 OAuth 2.0 網頁應用程式用戶端 ID。這個用戶端 ID 和應用程式用戶端 ID 不同。您可以在 Google API 控制台中查看或建立伺服器的用戶端 ID。
為應用程式啟用伺服器端 API 存取權
設定 Google 登入時,請使用
requestServerAuthCode
方法建構GoogleSignInOptions
物件,並使用requestScopes
方法指定應用程式後端需要存取的範圍。將 伺服器的用戶端 ID 傳遞至
requestServerAuthCode
方法。// Configure sign-in to request offline access to the user's ID, basic // profile, and Google Drive. The first time you request a code you will // be able to exchange it for an access token and refresh token, which // you should store. In subsequent calls, the code will only result in // an access token. By asking for profile access (through // DEFAULT_SIGN_IN) you will also get an ID Token as a result of the // code exchange. String serverClientId = getString(R.string.server_client_id); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER)) .requestServerAuthCode(serverClientId) .requestEmail() .build();
使用者成功登入後,請使用
getServerAuthCode
為使用者取得驗證碼:Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { GoogleSignInAccount account = task.getResult(ApiException.class); String authCode = account.getServerAuthCode(); // Show signed-un UI updateUI(account); // TODO(developer): send code to server and exchange for access/refresh/ID tokens } catch (ApiException e) { Log.w(TAG, "Sign-in failed", e); updateUI(null); }
使用 HTTPS POST 將驗證碼傳送至應用程式的後端:
HttpPost httpPost = new HttpPost("https://yourbackend.example.com/authcode"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("authCode", authCode)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); final String responseBody = EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e) { Log.e(TAG, "Error sending auth code to backend.", e); } catch (IOException e) { Log.e(TAG, "Error sending auth code to backend.", e); }
在應用程式的後端伺服器上,交換驗證碼以取得存取權和更新權杖。請使用存取權杖代表使用者呼叫 Google API,然後可選擇是否儲存更新權杖,方便在存取權杖過期時取得新的存取權杖。
如果您要求個人資料存取權,也會取得 ID 權杖,其中包含使用者的基本個人資料資訊。
例如:
Java
// (Receive authCode via HTTPS POST) if (request.getHeader("X-Requested-With") == null) { // Without the `X-Requested-With` header, this request could be forged. Aborts. } // Set path to the Web application client_secret_*.json file you downloaded from the // Google API Console: https://console.cloud.google.com/apis/credentials // You can also find your Web application client ID and client secret from the // console and specify them directly when you create the GoogleAuthorizationCodeTokenRequest // object. String CLIENT_SECRET_FILE = "/path/to/client_secret.json"; // Exchange auth code for access token GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE)); GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest( new NetHttpTransport(), JacksonFactory.getDefaultInstance(), "https://oauth2.googleapis.com/token", clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret(), authCode, REDIRECT_URI) // Specify the same redirect URI that you use with your web // app. If you don't have a web version of your app, you can // specify an empty string. .execute(); String accessToken = tokenResponse.getAccessToken(); // Use access token to call API GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken); Drive drive = new Drive.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), credential) .setApplicationName("Auth Code Exchange Demo") .build(); File file = drive.files().get("appfolder").execute(); // Get profile info from ID token GoogleIdToken idToken = tokenResponse.parseIdToken(); GoogleIdToken.Payload payload = idToken.getPayload(); String userId = payload.getSubject(); // Use this value as a key to identify a user. String email = payload.getEmail(); boolean emailVerified = Boolean.valueOf(payload.getEmailVerified()); String name = (String) payload.get("name"); String pictureUrl = (String) payload.get("picture"); String locale = (String) payload.get("locale"); String familyName = (String) payload.get("family_name"); String givenName = (String) payload.get("given_name");
Python
from apiclient import discovery import httplib2 from oauth2client import client # (Receive auth_code by HTTPS POST) # If this request does not have `X-Requested-With` header, this could be a CSRF if not request.headers.get('X-Requested-With'): abort(403) # Set path to the Web application client_secret_*.json file you downloaded from the # Google API Console: https://console.cloud.google.com/apis/credentials CLIENT_SECRET_FILE = '/path/to/client_secret.json' # Exchange auth code for access token, refresh token, and ID token credentials = client.credentials_from_clientsecrets_and_code( CLIENT_SECRET_FILE, ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'], auth_code) # Call Google API http_auth = credentials.authorize(httplib2.Http()) drive_service = discovery.build('drive', 'v3', http=http_auth) appfolder = drive_service.files().get(fileId='appfolder').execute() # Get profile info from ID token userid = credentials.id_token['sub'] email = credentials.id_token['email']