从您的应用后端访问 Google API

如果您希望服务器能够 代表用户调用 Google API,或在用户离线时调用 Google API。

准备工作

您必须完成基本的 Google 登录功能集成

为应用启用服务器端 API 访问权限

在 iOS 应用中访问 Google API 页面上 页面上,您的应用仅在客户端对用户进行身份验证;在本例中 您的应用只能在用户正在使用 。

按照本页介绍的程序,您的服务器就可以将 Google API 在用户离线时代表用户进行通话。例如,照片应用可以 通过在后端进行处理,增强用户 Google 相册影集中的照片 并将结果上传到其他影集。为此,您的服务器 需要访问令牌和刷新令牌。

要获取服务器的访问令牌和刷新令牌,您可以执行以下操作: 请求您的服务器用来交换的一次性授权代码 生成这两个词元。成功登录后,您会发现一次性代码为 GIDSignInResultserverAuthCode 属性。

  1. 获取服务器客户端 ID(如果尚未获取) 并在应用的 Info.plist 文件中(位于 OAuth 客户端 ID 下方)进行指定。

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

  2. 在您的登录回调中,检索一次性授权代码:

    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. 使用 HTTPS POST 将 serverAuthCode 字符串安全地传递到您的服务器。

  4. 在应用的后端服务器上,使用授权代码获取访问权限并刷新 词元。使用访问令牌以用户的名义调用 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']