เข้าถึง Google APIs จากแบ็กเอนด์ของแอป

โปรดทำตามขั้นตอนนี้หากต้องการให้เซิร์ฟเวอร์ทำการเรียก Google API ในนามของผู้ใช้หรือในขณะออฟไลน์ได้

ก่อนเริ่มต้น

คุณต้องทำการผสานรวม Google Sign-In พื้นฐานให้เสร็จสมบูรณ์

เปิดใช้การเข้าถึง API ฝั่งเซิร์ฟเวอร์สำหรับแอปของคุณ

ในหน้าเข้าถึง Google APIs ในแอป iOS แอปของคุณจะตรวจสอบสิทธิ์ผู้ใช้ในฝั่งไคลเอ็นต์เท่านั้น ในกรณีนี้ แอปจะเข้าถึง Google APIs ได้เฉพาะขณะที่ผู้ใช้กำลังใช้แอปอยู่เท่านั้น

ขั้นตอนที่อธิบายไว้ในหน้านี้ช่วยให้เซิร์ฟเวอร์เรียก Google API ในนามของผู้ใช้ได้ขณะที่ผู้ใช้ออฟไลน์ เช่น แอปรูปภาพอาจช่วยปรับปรุงรูปภาพในอัลบั้ม Google Photos ของผู้ใช้ โดยการประมวลผลบนเซิร์ฟเวอร์แบ็กเอนด์และอัปโหลดผลลัพธ์ไปยังอัลบั้มอื่น ในการดำเนินการ เซิร์ฟเวอร์ของคุณต้องมีโทเค็นเพื่อการเข้าถึงและโทเค็นการรีเฟรช

หากต้องการขอรับโทเค็นเพื่อการเข้าถึงและโทเค็นการรีเฟรชสำหรับเซิร์ฟเวอร์ คุณขอรหัสการให้สิทธิ์แบบครั้งเดียวที่เซิร์ฟเวอร์แลกเปลี่ยนกับโทเค็น 2 รายการนี้ หลังจากลงชื่อเข้าใช้สำเร็จ คุณจะเห็นรหัสแบบใช้ครั้งเดียวเป็นพร็อพเพอร์ตี้ serverAuthCode ของ GIDSignInResult

  1. หากยังไม่ได้ดำเนินการ ให้รับรหัสไคลเอ็นต์ของเซิร์ฟเวอร์และระบุรหัสนี้ในไฟล์ Info.plist ของแอป ด้านล่างรหัสไคลเอ็นต์ OAuth

    <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. ส่งสตริง serverAuthCode ไปยังเซิร์ฟเวอร์ของคุณอย่างปลอดภัยโดยใช้ HTTPS POST

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