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

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

시작하기 전에

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

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

iOS 앱에서 Google API에 액세스 페이지에서 앱은 클라이언트 측에서만 사용자를 인증합니다. 이 경우 사용자가 앱을 적극적으로 사용하는 동안에만 앱이 Google API에 액세스할 수 있습니다.

이 페이지에 설명된 절차를 사용하면 서버에서 사용자가 오프라인 상태일 때 사용자를 대신하여 Google API를 호출할 수 있습니다. 예를 들어 사진 앱은 백엔드 서버에서 사진을 처리하고 결과를 다른 앨범에 업로드하여 사용자의 Google 포토 앨범에 있는 사진을 개선할 수 있습니다. 이렇게 하려면 서버에 액세스 토큰과 갱신 토큰이 필요합니다.

서버의 액세스 토큰과 갱신 토큰을 가져오려면 서버에서 이 두 토큰으로 교환하는 일회성 승인 코드를 요청하면 됩니다. 로그인에 성공하면 일회성 코드가 serverAuthCode 속성으로 GIDSignInResult 표시됩니다.

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