서버 측 액세스 사용 설정

이전 Add Sign-In(로그인 추가)을 사용하여 앱이 클라이언트 측에서만 사용자를 인증합니다. 이 경우 사용자가 앱을 적극적으로 사용하는 동안에만 Google API에 액세스할 수 있습니다. 서버가 사용자를 대신하여 Google API를 호출할 수 있도록 하려면 사용자가 오프라인일 때 서버에 액세스하려면 토큰입니다.

시작하기 전에

  • 프로젝트 구성
  • 앱에 Google 로그인 버튼 추가
  • 백엔드 서버에 대한 OAuth 2.0 웹 애플리케이션 클라이언트 ID를 만듭니다. 이 클라이언트 ID가 앱의 클라이언트 ID와 다릅니다. 다음 위치에서 찾거나 새로 만들 수 있습니다. Google API 콘솔에서 서버의 클라이언트 ID를 확인할 수 있습니다.

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

  1. Google 로그인을 구성하면 requestServerAuthCode를 사용하여 GoogleSignInOptions 객체를 빌드합니다. 메서드를 사용하여 앱의 백엔드에서 액세스해야 하는 범위를 지정합니다. requestScopes 메서드를 사용하여 축소하도록 요청합니다.

    서버의 클라이언트 ID 전달 requestServerAuthCode 메서드에 전달합니다.

    // Configure sign-in to request offline access to the user's ID, basic
    // profile, and Google Drive. The first time you request a code you will
    // be able to exchange it for an access token and refresh token, which
    // you should store. In subsequent calls, the code will only result in
    // an access token. By asking for profile access (through
    // DEFAULT_SIGN_IN) you will also get an ID Token as a result of the
    // code exchange.
    String serverClientId = getString(R.string.server_client_id);
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
            .requestServerAuthCode(serverClientId)
            .requestEmail()
            .build();
  2. 사용자가 성공적으로 로그인하면 getServerAuthCode로 사용자의 인증 코드를 가져옵니다.

    Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
    try {
        GoogleSignInAccount account = task.getResult(ApiException.class);
        String authCode = account.getServerAuthCode();
    
        // Show signed-un UI
        updateUI(account);
    
        // TODO(developer): send code to server and exchange for access/refresh/ID tokens
    } catch (ApiException e) {
        Log.w(TAG, "Sign-in failed", e);
        updateUI(null);
    }
  3. HTTPS POST를 사용하여 앱의 백엔드에 인증 코드를 전송합니다.

    HttpPost httpPost = new HttpPost("https://yourbackend.example.com/authcode");
    
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("authCode", authCode));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
        HttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        final String responseBody = EntityUtils.toString(response.getEntity());
    } catch (ClientProtocolException e) {
        Log.e(TAG, "Error sending auth code to backend.", e);
    } catch (IOException e) {
        Log.e(TAG, "Error sending auth code to backend.", e);
    }
    
  4. 앱의 백엔드 서버에서 액세스 및 새로고침을 위해 인증 코드를 교환합니다. 토큰입니다. 액세스 토큰을 사용하여 사용자 대신 Google API를 호출합니다. 필요한 경우, 갱신 토큰을 저장하여 사용자가 액세스할 수 없을 때 새 액세스 토큰을 액세스 토큰이 만료된 경우

    프로필 액세스를 요청한 경우 다음이 포함된 ID 토큰도 받게 됩니다. 사용자의 기본 프로필 정보를 입력합니다.

    예를 들면 다음과 같습니다.

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