Access Google APIs from your app backend

Follow this procedure if you want your servers to be able to make Google API calls on behalf of users or while they are offline.

Before you begin

You must complete the basic Google Sign-In integration.

Enable server-side API access for your app

On the Access Google APIs in an iOS app page, your app authenticates the user on the client side only; in that case, your app is able to access Google APIs only while the user is actively using your app.

With the procedure described on this page, your servers can make Google API calls on behalf of users while they are offline. For example, a photo app could enhance a photo in a user's Google Photos album by processing it on a backend server and uploading the result to another album. To do this, your server requires an access token and a refresh token.

To obtain an access token and refresh token for your server, you can request a one-time authorization code that your server exchanges for these two tokens. You request the one-time code by specifying your server's client ID along with your other GIDSignIn parameters. After a successful sign-in, you will find the one-time code as the serverAuthCode property of GIDGoogleUser.

  1. If you haven't already, get a server client ID and specify it when you initialize your app's GIDConfiguration object:


    let signInConfig = GIDConfiguration.init(
        clientID: "YOUR_IOS_CLIENT_ID",
        serverClientID: "YOUR_SERVER_CLIENT_ID"


    signInConfig = [[GIDConfiguration alloc] initWithClientID:@"YOUR_IOS_CLIENT_ID"
  2. In your sign-in callback, retrieve the one-time authorization code:


    GIDSignIn.sharedInstance.signIn(with: signInConfig, presenting: self) { user, error in
        guard error == nil else { return }
        guard let user = user else { return }
        let authCode = user.serverAuthCode


    [GIDSignIn.sharedInstance signInWithConfiguration:signInConfig
                                             callback:^(GIDGoogleUser * _Nullable user,
                                                        NSError * _Nullable error) {
          if (error) { return; }
          if (user == nil) { return; }
          NSString *authCode = user.serverAuthCode
  3. Securely pass the serverAuthCode string to your server using HTTPS POST.

  4. On your app's backend server, exchange the auth code for access and refresh tokens. Use the access token to call Google APIs on behalf of the user and, optionally, store the refresh token to acquire a new access token when the access token expires.

    For example:

    // (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:
    // 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 =
            JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE));
    GoogleTokenResponse tokenResponse =
              new GoogleAuthorizationCodeTokenRequest(
                  new NetHttpTransport(),
                  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.
    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")
    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");
    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'):
    # Set path to the Web application client_secret_*.json file you downloaded from the
    # Google API Console:
    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(
        ['', 'profile', 'email'],
    # Call Google API
    http_auth = credentials.authorize(httplib2.Http())
    drive_service ='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']