Một số dịch vụ của Google, chẳng hạn như Drive, Gmail và nhiều dịch vụ khác, cung cấp các API công khai mà bạn có thể dùng để tạo ứng dụng giúp người dùng làm việc với dữ liệu của họ trong các dịch vụ này. Để truy cập những dịch vụ này, ứng dụng phải triển khai một trong các luồng ứng dụng OAuth 2.0 để có được sự đồng ý của người dùng và lấy mã truy cập để cấp quyền truy cập vào các API.
Bạn có thể sử dụng thư viện Đăng nhập của Google. Thư viện này triển khai quy trình OAuth 2.0 cho bạn để nhận mã truy cập cho người dùng đã đăng nhập.
Trước khi bắt đầu
Bạn phải hoàn tất tích hợp Đăng nhập bằng Google cơ bản.
1. Kiểm tra xem phạm vi nào đã được cấp
Trước khi thực hiện lệnh gọi đến một API của Google, hãy kiểm tra xem phạm vi nào đã được cấp cho ứng dụng của bạn bằng thuộc tính grantedScopes
của GIDGoogleUser
:
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
}
Dựa trên việc người dùng đã cấp một phạm vi nhất định hay chưa, bạn có thể cần yêu cầu một phạm vi bổ sung để hỗ trợ một lượt tương tác cụ thể nào đó.
2. Yêu cầu thêm phạm vi
Nếu bạn cần yêu cầu phạm vi bổ sung, hãy gọi addScopes:presentingViewController:completion
hoặc addScopes:presentingWindow:completion
để yêu cầu người dùng cấp quyền truy cập bổ sung cho ứng dụng của bạn.
Ví dụ: để yêu cầu quyền truy cập chỉ đọc vào tệp trong Drive của người dùng:
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. Thực hiện lệnh gọi API bằng mã thông báo mới
Để đảm bảo rằng các lệnh gọi API Google luôn có đính kèm mã truy cập chưa hết hạn, hãy gói các lệnh gọi trong một khối 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];
}];
Sử dụng mã truy cập để gọi API, bằng cách đưa mã truy cập vào tiêu đề của yêu cầu REST hoặc gRPC (Authorization: Bearer ACCESS_TOKEN
) hoặc bằng cách sử dụng trình uỷ quyền tìm nạp với Thư viện ứng dụng API của Google.