某些 Google 服务(例如云端硬盘、Gmail 和许多其他服务)提供公共 API,您可以使用这些 API 来创建帮助用户使用这些服务中的数据的应用程序。要访问这些服务,应用程序必须实施 OAuth 2.0 客户端流程之一,以获得用户的同意并获取访问令牌,从而授予对 API 的访问权限。
您可以使用为您实现 OAuth 2.0 流程的 Google 登录库来获取登录用户的访问令牌。
在你开始之前
您必须完成基本的 Google 登录集成。
1. 检查哪些范围已被授予
您对谷歌API的调用之前,请检查范围已授予您的应用程序,使用grantedScopes
财产GIDGoogleUser
:
迅速
let driveScope = "https://www.googleapis.com/auth/drive.readonly"
let grantedScopes = user.grantedScopes
if grantedScopes == nil || !grantedScopes!.contains(driveScope) {
// Request additional Drive scope.
}
目标-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:callback;
要求用户授予您的应用额外的访问权限。
例如,要请求对用户的云端硬盘进行只读访问:
迅速
let additionalScopes = ["https://www.googleapis.com/auth/drive.readonly"]
GIDSignIn.sharedInstance.addScopes(additionalScopes, presenting: self) { user, error in
guard error == nil else { return }
guard let user = user else { return }
// Check if the user granted access to the scopes you requested.
}
目标-C
NSArray *additionalScopes = @[ @"https://www.googleapis.com/auth/drive.readonly" ];
[GIDSignIn.sharedInstance addScopes:additionalScopes
presentingViewController:self
callback:^(GIDGoogleUser * _Nullable user,
NSError * _Nullable error) {
if (error) { return; }
if (user == nil) { return; }
// Check if the user granted access to the scopes you requested.
}];
3. 使用新令牌进行 API 调用
为确保您的 Google API 调用始终附加未过期的访问令牌,请将调用包装在doWithFreshTokens:
块中:
迅速
user.authentication.do { authentication, error in
guard error == nil else { return }
guard let authentication = authentication else { return }
// Get the access token to attach it to a REST or gRPC request.
let accessToken = authentication.accessToken
// Or, get an object that conforms to GTMFetcherAuthorizationProtocol for
// use with GTMAppAuth and the Google APIs client library.
let authorizer = authentication.fetcherAuthorizer()
}
目标-C
[user.authentication doWithFreshTokens:^(GIDAuthentication * _Nullable authentication,
NSError * _Nullable error) {
if (error) { return; }
if (authentication == nil) { return; }
// Get the access token to attach it to a REST or gRPC request.
NSString *accessToken = authentication.accessToken;
// Or, get an object that conforms to GTMFetcherAuthorizationProtocol for
// use with GTMAppAuth and the Google APIs client library.
id<GTMFetcherAuthorizationProtocol> authorizer = [authentication fetcherAuthorizer];
}];
使用访问令牌调用 API,方法是在 REST 或 gRPC 请求的标头中包含访问令牌( Authorization: Bearer ACCESS_TOKEN
),或者通过将Authorization: Bearer ACCESS_TOKEN
授权器与Google API 客户端库结合使用。