アプリのバックエンドから Google API にアクセスする

ユーザーに代わって、またはユーザーがオフラインのときに、サーバーが Google API 呼び出しを行えるようにするには、次の手順に沿って操作します。

始める前に

Google ログインの基本的な統合を完了する必要があります。

アプリのサーバーサイド API アクセスを有効にする

iOS アプリで Google API にアクセスするページでは、アプリはクライアントサイドでのみユーザーを認証します。この場合、アプリはユーザーがアプリを積極的に使用している間のみ Google API にアクセスできます。

このページで説明する手順に沿って、ユーザーがオフラインのときに、サーバーがユーザーに代わって Google API 呼び出しを行うことができます。たとえば、写真アプリは、バックエンド サーバーで処理して結果を別のアルバムにアップロードすることで、ユーザーの Google フォト アルバム内の写真を補正できます。これを行うには、サーバーにアクセス トークンと更新トークンが必要です。

サーバーのアクセス トークンと更新トークンを取得するには、サーバーがこの 2 つのトークンと交換するワンタイム認証コードをリクエストします。ログインに成功すると、GIDSignInResultserverAuthCode プロパティとしてワンタイム コードが返されます。

  1. まだ取得していない場合は、サーバー クライアント ID を取得し、アプリの Info.plist ファイルの OAuth クライアント ID の下に指定します。

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

  2. ログイン コールバックで、1 回限りの認証コードを取得します。

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