Truy cập API của Google từ phần phụ trợ ứng dụng của bạn

Hãy làm theo quy trình này nếu bạn muốn máy chủ của mình có thể thực hiện các lệnh gọi API của Google thay mặt cho người dùng hoặc khi họ không kết nối mạng.

Trước khi bắt đầu

Bạn phải hoàn tất quy trình tích hợp cơ bản đối với tính năng Đăng nhập bằng Google.

Bật quyền truy cập API phía máy chủ cho ứng dụng của bạn

Trên trang Truy cập vào các API của Google trong ứng dụng iOS, ứng dụng của bạn chỉ xác thực người dùng ở phía máy khách; trong trường hợp đó, ứng dụng của bạn chỉ có thể truy cập vào các API của Google khi người dùng đang sử dụng ứng dụng của bạn.

Với quy trình được mô tả trên trang này, các máy chủ của bạn có thể thực hiện lệnh gọi Google API thay cho người dùng khi họ không kết nối mạng. Ví dụ: một ứng dụng ảnh có thể cải thiện một bức ảnh trong album Google Photos của người dùng bằng cách xử lý bức ảnh đó trên một máy chủ phụ trợ và tải kết quả lên một album khác. Để thực hiện việc này, máy chủ của bạn cần có mã truy cập và mã làm mới.

Để nhận mã truy cập và mã làm mới cho máy chủ, bạn có thể yêu cầu mã uỷ quyền dùng một lần mà máy chủ của bạn sẽ trao đổi để lấy hai mã thông báo này. Sau khi đăng nhập thành công, bạn sẽ thấy mã dùng một lần dưới dạng thuộc tính serverAuthCode của GIDSignInResult.

  1. Nếu chưa, hãy lấy mã ứng dụng khách máy chủ và chỉ định mã này trong tệp Info.plist của ứng dụng, bên dưới mã ứng dụng OAuth.

    <key>GIDServerClientID</key>
    <string>YOUR_SERVER_CLIENT_ID</string>

  2. Trong lệnh gọi lại đăng nhập, hãy truy xuất mã uỷ quyền dùng một lần:

    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;
    }];
    
  3. Truyền chuỗi serverAuthCode một cách an toàn đến máy chủ của bạn bằng cách sử dụng yêu cầu POST qua HTTPS.

  4. Trên máy chủ phụ trợ của ứng dụng, hãy trao đổi mã uỷ quyền để lấy mã truy cập và mã làm mới. Sử dụng mã truy cập để gọi các API của Google thay mặt cho người dùng và tuỳ ý lưu trữ mã làm mới để lấy mã truy cập mới khi mã truy cập hết hạn.

    Ví dụ:

    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']