Uygulamanızın arka ucundan Google API'lerine erişme

Sunucularınızın şunları yapmasına izin vermek için bu prosedürü uygulayın: Kullanıcılar adına veya kullanıcılar çevrimdışıyken Google API çağrıları.

Başlamadan önce

Temel Google ile Oturum Açma entegrasyonunu tamamlamanız gerekir.

Uygulamanız için sunucu tarafı API erişimini etkinleştirme

iOS uygulamasındaki Google API'lerine erişme başlıklı makalede sayfası, uygulamanız yalnızca istemci tarafında kullanıcının kimliğini doğrular; bu durumda, Uygulamanız yalnızca kullanıcı aktif olarak kullanırken Google API'lerine erişebiliyor en iyi şekilde yararlanabilirsiniz.

Bu sayfada açıklanan prosedürle, sunucularınız Google API'sini çevrimdışıyken arama yapan kullanıcılara gösterilir. Örneğin bir fotoğraf uygulaması bir kullanıcının Google Fotoğraflar albümündeki fotoğrafı arka uçta işleyerek iyileştirir sunucuya yüklemek ve sonucu başka bir albüme yüklemektir. Bunun için sunucunuz erişim jetonu ve yenileme jetonu gerektirir.

Sunucunuz için erişim jetonu ve yenileme jetonu almak için: Sunucunuzun değişim amaçlı olarak kullanacağı tek seferlik yetkilendirme kodu için istekte bulunun. çok önemli. Başarılı bir oturum açma işleminden sonra tek kullanımlık kodu şu şekilde görürsünüz: GIDSignInResult öğesinin serverAuthCode özelliği.

  1. Henüz yapmadıysanız bir sunucu istemci kimliği alın ve bunu uygulamanızın Info.plist dosyasında, OAuth istemci kimliğinizin altında belirtin.

    <key>GIDServerClientID</key>
    <string>YOUR_SERVER_CLIENT_ID</string>
    

  2. Oturum açma geri çağırmanızda tek seferlik yetkilendirme kodunu alın:

    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 kullanarak serverAuthCode dizesini sunucunuza güvenli bir şekilde iletin.

  4. Uygulamanızın arka uç sunucusunda erişim için yetkilendirme kodunu değiştirip yenileyin jeton. Kullanıcı adına Google API'lerini çağırmak için erişim jetonunu kullanın ve isteğe bağlı olarak, yeni bir erişim jetonu almak için yeni bir erişim jetonunun süresi dolar.

    Örneğin:

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