앱 백엔드에서 Google API에 액세스

서버가 사용자 대신 또는 사용자가 오프라인 상태일 때 Google API를 호출할 수 있게 하려면 다음 절차를 따르세요.

시작하기 전에

기본 Google 로그인 통합을 완료해야 합니다.

앱에 서버 측 API 액세스 사용 설정

iOS 앱에서 Google API 액세스 페이지에서 앱은 클라이언트 측에서만 사용자를 인증합니다. 이 경우 사용자가 앱을 활발히 사용하는 동안에만 앱이 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']