Google Sign-In for server-side apps

To use Google services on behalf of a user when the user is offline, you must use a hybrid server-side flow where a user authorizes your app on the client side using the JavaScript API client and you send a special one-time authorization code to your server. Your server exchanges this one-time-use code to acquire its own access and refresh tokens from Google for the server to be able to make its own API calls, which can be done while the user is offline. This one-time code flow has security advantages over both a pure server-side flow and over sending access tokens to your server.

The sign-in flow for obtaining an access token for your server-side application is illustrated below.

One-time codes have several security advantages. With codes, Google provides tokens directly to your server without any intermediaries. Although we don't recommend leaking codes, they are very hard to use without your client secret. Keep your client secret secret!

Implementing the one-time-code flow

The Google Sign-In button provides both an access token and an authorization code. The code is a one-time code that your server can exchange with Google's servers for an access token.

The following sample code demonstrates how to do the one-time-code flow.

Authenticating Google Sign-In with one-time-code flow requires you to:

Step 1: Create a client ID and client secret

To create a client ID and client secret, create a Google Developers Console project, enable the Google API, and register your JavaScript origins:

  1. Go to the Google Developers Console .
  2. Select a project, or create a new one by selecting Create a Project from your projects list:

    Note: Use a single project to hold all platform instances of your app (Android, iOS, web, etc.), each with a different Client ID.

    1. In the Project name field, type in a name for your project.
    2. Your Project ID is created by the console for you.
    3. Click the Create button and wait for the project to be created.
  3. In the sidebar under "APIs & auth", select Credentials, and click the OAuth consent screen tab.
    1. Choose an Email Address, specify a Product Name, and click Save.
  4. In the sidebar under "APIs & auth", select Credentials.
  5. Click Create a new Client ID — a dialog box appears.
    Register the origins from which your app is allowed to access the Google APIs, as follows. An origin is a unique combination of protocol, hostname, and port.
    1. In the Application type section of the dialog, select Web application.
    2. In the Authorized JavaScript origins field, enter the origin for your app. You can enter multiple origins to allow for your app to run on different protocols, domains, or subdomains. Wildcards are not allowed. In the example below, the second URL could be a production URL.
    3. In the Authorized redirect URI field, delete the default value. Redirect URIs are not used with JavaScript APIs.
    4. Click the Create Client ID button.
  6. In the resulting Client ID for web application section, copy the Client ID that your app will need to use to access the APIs.

Step 2: Include the Google platform library on your page

Include the following scripts that demonstrate an anonymous function that inserts a script into the DOM of this index.html web page.

<!-- The top of file index.html -->
<html itemscope itemtype="http://schema.org/Article">
  <!-- BEGIN Pre-requisites -->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  <script src="https://apis.google.com/js/client:platform.js?onload=start" async defer>
  <!-- END Pre-requisites -->

Step 3: Initialize the GoogleAuth object

Load the auth2 library and call gapi.auth2.init() to initialize the GoogleAuth object. Specify your client ID and the scopes you want to request when you call init().

<!-- Continuing the <head> section -->
    function start() {
      gapi.load('auth2', function() {
        auth2 = gapi.auth2.init({
          client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
          // Scopes to request in addition to 'profile' and 'email'
          //scope: 'additional_scope'
  <!-- ... -->

Step 4: Add the sign-in button to your page

Add the sign-in button to your web page and set the redirecturi to postmessage to enable the one-time-code flow.

<!-- Add where you want your sign-in button to render -->
<!-- Use an image that follows the branding guidelines in a real app -->
<button id="signinButton">Sign in with Google</button>
  $('#signinButton').click(function() {
    // signInCallback defined in step 6.
    auth2.grantOfflineAccess({'redirect_uri': 'postmessage'}).then(signInCallback);
<div id="result"></div>

You can also send the authorization response directly to your server by specifying the URI of your server's authorization code handler for the redirect_uri parameter. If you do this, skip step 6.

Step 5: Sign in the user

The user clicks the sign-in button and grants your app access to the permissions that you requested. Then, the callback function that you specified in the grantOfflineAccess().then() method is passed a JSON object with an authorization code. For example:


Step 6: Send the authorization code to the server

The code is your one-time code that your server can exchange for its own access token and refresh token. You can only obtain a refresh token after the user has been presented an authorization dialog requesting offline access. You must store the refresh token that you retrieve for later use because subsequent exchanges will return null for the refresh token. This flow provides increased security over your standard OAuth 2.0 flow.

Access tokens are always returned with the exchange of a valid authorization code.

The following script defines a callback function for the sign-in button. When a sign-in is successful, the function stores the access token for client-side use and sends the one-time code to your server on the same domain.

<!-- Last part of BODY element in file index.html -->
function signInCallback(authResult) {
  if (authResult['code']) {

    // Hide the sign-in button now that the user is authorized, for example:
    $('#signinButton').attr('style', 'display: none');

    // Send the code to the server
      type: 'POST',
      url: 'http://example.com/storeauthcode',
      contentType: 'application/octet-stream; charset=utf-8',
      success: function(result) {
        // Handle or verify the server response.
      processData: false,
      data: authResult['code']
  } else {
    // There was an error.

Your server accepts the one-time code from the client and exchanges it for an access token and a refresh token, which the server uses to call Google APIs on behalf of the user.