Accéder aux API Google à partir du backend de votre application

Suivez cette procédure si vous souhaitez que vos serveurs puissent effectuer des appels d'API Google au nom des utilisateurs ou hors connexion.

Avant de commencer

Vous devez procéder à l'intégration de base de Google Sign-In.

Activer l'accès aux API côté serveur pour votre application

Sur la page Accéder aux API Google dans une application iOS, votre application authentifie l'utilisateur uniquement côté client. Dans ce cas, votre application ne peut accéder aux API Google que lorsque l'utilisateur l'utilise activement.

La procédure décrite sur cette page permet à vos serveurs d'effectuer des appels d'API Google au nom des utilisateurs lorsqu'ils sont hors connexion. Par exemple, une application photo peut améliorer une photo de l'album Google Photos d'un utilisateur en la traitant sur un serveur backend et en important le résultat dans un autre album. Pour ce faire, votre serveur nécessite un jeton d'accès et un jeton d'actualisation.

Pour obtenir un jeton d'accès et un jeton d'actualisation pour votre serveur, vous pouvez demander un code d'autorisation à usage unique que votre serveur échange contre ces deux jetons. Une fois la connexion établie, vous verrez le code à usage unique en tant que propriété serverAuthCode de GIDSignInResult.

  1. Si vous ne l'avez pas déjà fait, obtenez un ID client de serveur et spécifiez-le dans le fichier Info.plist de votre application, sous votre ID client OAuth.

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

  2. Dans votre rappel de connexion, récupérez le code d'autorisation à usage unique:

    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. Transmettez de manière sécurisée la chaîne serverAuthCode à votre serveur à l'aide de HTTPS POST.

  4. Sur le serveur backend de votre application, échangez le code d'autorisation contre des jetons d'accès et d'actualisation. Utilisez le jeton d'accès pour appeler les API Google au nom de l'utilisateur et, éventuellement, stocker le jeton d'actualisation pour acquérir un nouveau jeton d'accès lorsque celui-ci expire.

    Exemple :

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