如果您希望伺服器能夠代表使用者或離線時發出 Google API 呼叫,請按照下列程序操作。
事前準備
您必須完成基本 Google 登入整合。
為應用程式啟用伺服器端 API 存取權
在「在 iOS 應用程式中存取 Google API」頁面上,應用程式只會在用戶端驗證使用者;在這種情況下,應用程式只有在使用者主動使用應用程式時才能存取 Google API。
按照本頁所述的程序進行,您的伺服器可在使用者離線時,代表使用者發出 Google API 呼叫。舉例來說,相片應用程式可透過後端伺服器處理相片,並將結果上傳至另一個相簿,藉此強化使用者的 Google 相簿相簿中的相片。如果要這麼做,您的伺服器會需要存取權杖和更新權杖。
如要為伺服器取得存取權杖和更新權杖,您可以要求伺服器交換這兩個權杖的一次性授權碼。成功登入後,您會看到一次性程式碼,做為 GIDSignInResult
的 serverAuthCode
屬性。
如果您尚未取得伺服器用戶端 ID,請先在應用程式的
Info.plist
檔案中 (OAuth 用戶端 ID 下方) 指定這個 ID。<key>GIDServerClientID</key> <string>YOUR_SERVER_CLIENT_ID</string>
在登入回呼中,擷取一次性授權碼:
Swift
GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in guard error == nil else { return } guard let signInResult = signInResult else { return } let authCode = signInResult.serverAuthCode }
Objective-C
[GIDSignIn.sharedInstance signInWithPresentingViewController:self completion:^(GIDSignInResult * _Nullable signInResult, NSError * _Nullable error) { if (error) { return; } if (signInResult == nil) { return; } NSString *authCode = signInResult.serverAuthCode; }];
使用 HTTPS POST 安全地將
serverAuthCode
字串傳遞至伺服器。在應用程式的後端伺服器上,以驗證碼交換存取權及更新權杖。使用存取權杖以代表使用者呼叫 Google API,並視需要儲存更新權杖以在存取權杖過期時取得新的存取權杖。
範例如下:
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']