部分 Google 服務 (例如雲端硬碟、Gmail 和許多其他服務) 提供公開 API,可用來建立應用程式來協助使用者在這些服務中使用自己的資料。要存取這些服務,應用程式必須執行其中一項 OAuth 2.0 用戶端流程,以取得使用者的同意聲明並取得存取憑證,以授予 API 存取權。
你可以使用 Google 登入程式庫,為您導入 OAuth 2.0 流程,以取得已登入使用者的存取憑證。
事前準備
您必須完成基本 Google 登入整合功能。
1. 查看已授予哪些範圍
呼叫 Google API 之前,請使用 GIDGoogleUser
的 grantedScopes
屬性,檢查已授予應用程式的範圍:
Swift
let driveScope = "https://www.googleapis.com/auth/drive.readonly"
let grantedScopes = user.grantedScopes
if grantedScopes == nil || !grantedScopes!.contains(driveScope) {
// Request additional Drive scope.
}
Objective-C
NSString *driveScope = @"https://www.googleapis.com/auth/drive.readonly";
// Check if the user has granted the Drive scope
if (![user.grantedScopes containsObject:driveScope]) {
// request additional drive scope
}
根據使用者是否已授予特定範圍,您可能需要要求其他範圍才能支援特定互動。
2. 要求其他範圍
如需要求其他範圍,請呼叫 addScopes:presentingViewController:completion
或 addScopes:presentingWindow:completion
,要求使用者授予應用程式額外存取權。
舉例來說,您可以要求取得使用者雲端硬碟檔案的唯讀存取權:
Swift
let additionalScopes = ["https://www.googleapis.com/auth/drive.readonly"]
guard let currentUser = GIDSignIn.sharedInstance.currentUser else {
return ; /* Not signed in. */
}
currentUser.addScopes(additionalScopes, presenting: self) { signInResult, error in
guard error == nil else { return }
guard let signInResult = signInResult else { return }
// Check if the user granted access to the scopes you requested.
}
Objective-C
NSArray *additionalScopes = @[ @"https://www.googleapis.com/auth/drive.readonly" ];
GIDGoogleUser *currentUser = GIDSignIn.sharedInstance.currentUser;
[currentUser addScopes:additionalScopes
presentingViewController:self
completion:^(GIDSignInResult * _Nullable signInResult,
NSError * _Nullable error) {
if (error) { return; }
if (signInResult == nil) { return; }
// Check if the user granted access to the scopes you requested.
}];
3. 使用更新過的憑證發出 API 呼叫
為確保 Google API 呼叫一律附加了未過期的存取憑證,請將呼叫納入 refreshTokensIfNeededWithCompletion:
區塊中:
Swift
currentUser.refreshTokensIfNeeded { user, error in
guard error == nil else { return }
guard let user = user else { return }
// Get the access token to attach it to a REST or gRPC request.
let accessToken = user.accessToken.tokenString
// Or, get an object that conforms to GTMFetcherAuthorizationProtocol for
// use with GTMAppAuth and the Google APIs client library.
let authorizer = user.fetcherAuthorizer()
}
Objective-C
[currentUser refreshTokensIfNeededWithCompletion:^(
GIDGoogleUser * _Nullable user,
NSError * _Nullable error) {
if (error) { return; }
if (user == nil) { return; }
// Get the access token to attach it to a REST or gRPC request.
NSString *accessToken = user.accessToken.tokenString;
// Or, get an object that conforms to GTMFetcherAuthorizationProtocol for
// use with GTMAppAuth and the Google APIs client library.
id<GTMFetcherAuthorizationProtocol> authorizer = [user fetcherAuthorizer];
}];
使用存取憑證以呼叫 API 的方式:在 REST 或 gRPC 要求的標題中加入存取權杖 (Authorization: Bearer ACCESS_TOKEN
),或使用擷取器授權者搭配 Google API 用戶端程式庫。