앱 백엔드에서 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']