Check out our new one-tap sign-up and auto sign-in experience for the web!

OAuth 2.0 for Client-side Web Applications

This document explains how to implement OAuth 2.0 authorization to access Google APIs from a JavaScript web application. OAuth 2.0 allows users to share specific data with an application while keeping their usernames, passwords, and other information private. For example, an application can use OAuth 2.0 to obtain permission from users to store files in their Google Drives.

This OAuth 2.0 flow is called the implicit grant flow. It is designed for applications that access APIs only while the user is present at the application. These applications are not able to store confidential information.

In this flow, your app opens a Google URL that uses query parameters to identify your app and the type of API access that the app requires. You can open the URL in the current browser window or a popup. The user can authenticate with Google and grant the requested permissions. Google then redirects the user back to your app. The redirect includes an access token, which your app verifies and then uses to make API requests.

Prerequisites

Enable APIs for your project

Any application that calls Google APIs needs to enable those APIs in the API Console. To enable the appropriate APIs for your project:

  1. Open the Library page in the API Console.
  2. Select the project associated with your application. Create a project if you do not have one already.
  3. Use the Library page to find each API that your application will use. Click on each API and enable it for your project.

Create authorization credentials

Any application that uses OAuth 2.0 to access Google APIs must have authorization credentials that identify the application to Google's OAuth 2.0 server. The following steps explain how to create credentials for your project. Your applications can then use the credentials to access APIs that you have enabled for that project.

  1. Open the Credentials page in the API Console.
  2. Click Create credentials > OAuth client ID.
  3. Complete the form. Set the application type to Web application. Applications that use JavaScript to make authorized Google API requests must specify authorized JavaScript origins. The origins identify the domains from which your application can send API requests.

Identify access scopes

Scopes enable your application to only request access to the resources that it needs while also enabling users to control the amount of access that they grant to your application. Thus, there may be an inverse relationship between the number of scopes requested and the likelihood of obtaining user consent.

Before you start implementing OAuth 2.0 authorization, we recommend that you identify the scopes that your app will need permission to access.

The OAuth 2.0 API Scopes document contains a full list of scopes that you might use to access Google APIs.

Obtaining OAuth 2.0 access tokens

The following steps show how your application interacts with Google's OAuth 2.0 server to obtain a user's consent to perform an API request on the user's behalf. Your application must have that consent before it can execute a Google API request that requires user authorization.

Step 1: Configure the client object

If you are using Google APIs client library for JavaScript to handle the OAuth 2.0 flow, your first step is to configure the gapi.auth2 and gapi.client objects. These objects enable your application to obtain user authorization and to make authorized API requests.

The client object identifies the scopes that your application is requesting permission to access. These values inform the consent screen that Google displays to the user. The Choosing access scopes section provides information about how to determine which scopes your application should request permission to access.

JS Client Library

The JavaScript client library simplifies numerous aspects of the authorization process:

  1. It creates the redirect URL for Google's authorization server and provides a method to direct the user to that URL.
  2. It handles the redirect from that server back to your application.
  3. It validates the access token returned by the authorization server.
  4. It stores the access token that the authorization server sends to your application and retrieves it when your app subsequently makes authorized API calls.

The code snippet below is an excerpt from the complete example shown later in this document. This code initializes the gapi.client object, which your application would later use to make API calls. When that object is created, the gapi.auth2 object, which your application uses to check and monitor the user's authorization status, is also initialized.

The call to gapi.client.init specifies the following fields:

  • The apiKey and clientId values specify your application's authorization credentials. As discussed in the creating authorization credentials section, these values can be obtained in the API Console. Note that the clientId is required if your application makes authorized API requests. Applications that only make unauthorized requests can just specify an API key.

  • The scope field specifies a space-delimited list of access scopes that correspond to the resources that your application needs to access. These values inform the consent screen that Google displays to the user.

    We recommend that your application request access to authorization scopes in context whenever possible. By requesting access to user data in context, via incremental authorization, you help users to more easily understand why your application needs the access it is requesting.

  • The discoveryDocs field identifies a list of API Discovery documents that your application uses. A Discovery document describes the surface of an API, including its resource schemas, and the JavaScript client library uses that information to generate methods that applications can use. In this example, the code retrieves the discovery document for version 3 of the Google Drive API.

After the gapi.client.init call completes, the code sets the GoogleAuth variable to identify the Google Auth object. Finally, the code sets a listener that calls a function when the user's sign-in status changes. (That function is not defined in the snippet.)

var GoogleAuth; // Google Auth object.
function initClient() {
  gapi.client.init({
      'apiKey': 'YOUR_API_KEY',
      'clientId': 'YOUR_CLIENT_ID',
      'scope': 'https://www.googleapis.com/auth/drive.metadata.readonly',
      'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
  }).then(function () {
      GoogleAuth = gapi.auth2.getAuthInstance();

      // Listen for sign-in state changes.
      GoogleAuth.isSignedIn.listen(updateSigninStatus);
  });
}

OAuth 2.0 Endpoints

If you are directly accessing the OAuth 2.0 endpoints, you can proceed to the next step.

Step 2: Redirect to Google's OAuth 2.0 server

To request permission to access a user's data, redirect the user to Google's OAuth 2.0 server.

JS Client Library

Call the GoogleAuth.signIn() method to direct the user to Google's authorization server.

GoogleAuth.signIn();

In practice, your application might set a Boolean value to determine whether to call the signIn() method before attempting to make an API call.

The code snippet below demonstrates how you would initiate the user authorization flow. Note the following points about the snippet:

  • The GoogleAuth object referenced in the code is the same as the global variable defined in the code snippet in step 1.

  • The updateSigninStatus function is a listener that listens for changes to the user's authorization status. Its role as a listener was also defined in the code snippet in step 1:

    GoogleAuth.isSignedIn.listen(updateSigninStatus);
  • The snippet defines two additional global variables:

    • isAuthorized is a Boolean variable that indicates whether the user is already signed in. This value can be set when the app loads and updated if the user signs in or out of the app.

      In this snippet, the sendAuthorizedApiRequest function checks the variable's value to determine whether the app should attempt an API request that requires authorization or prompt the user to authorize the app.

    • currentApiRequest is an object that stores details about the last API request that the user attempted. The object's value is set when the app calls the sendAuthorizedApiRequest function.

      If the user has authorized the app, the request is executed right away. Otherwise, the function redirects the user to sign in. After the user signs in, the updateSignInStatus function calls sendAuthorizedApiRequest, passing in the same request that was attempted before the authorization flow started.

var isAuthorized;
var currentApiRequest;

/**
 * Store the request details. Then check to determine whether the user
 * has authorized the application.
 *   - If the user has granted access, make the API request.
 *   - If the user has not granted access, initiate the sign-in flow.
 */
function sendAuthorizedApiRequest(requestDetails) {
  currentApiRequest = requestDetails;
  if (isAuthorized) {
    // Make API request
    // gapi.client.request(requestDetails)

    // Reset currentApiRequest variable.
    currentApiRequest = {};
  } else {
    GoogleAuth.signIn();
  }
}

/**
 * Listener called when user completes auth flow. If the currentApiRequest
 * variable is set, then the user was prompted to authorize the application
 * before the request executed. In that case, proceed with that API request.
 */
function updateSigninStatus(isSignedIn) {
  if (isSignedIn) {
    isAuthorized = true;
    if (currentApiRequest) {
      sendAuthorizedApiRequest(currentApiRequest);
    }
  } else {
    isAuthorized = false;
  }
}

OAuth 2.0 Endpoints

Generate a URL to request access from Google's OAuth 2.0 endpoint at https://accounts.google.com/o/oauth2/v2/auth. This endpoint is accessible over HTTPS; plain HTTP connections are refused.

The Google authorization server supports the following query string parameters for web server applications:

Parameters
client_id Required. The client ID for your application. You can find this value in the API Console.
redirect_uri Required. Determines where the API server redirects the user after the user completes the authorization flow. The value must exactly match one of the redirect_uri values listed for your project in the API Console. Note that the http or https scheme, case, and trailing slash ('/') must all match.
response_type Required. JavaScript applications need to set the parameter's value to token. This instructs the Google Authorization Server to return the access token as a name=value pair in the hash (#) fragment of the URI to which the user is redirected after completing the authorization process.
scope Required. A space-delimited list of scopes that identify the resources that your application could access on the user's behalf. These values inform the consent screen that Google displays to the user.

Scopes enable your application to only request access to the resources that it needs while also enabling users to control the amount of access that they grant to your application. Thus, there is an inverse relationship between the number of scopes requested and the likelihood of obtaining user consent.

The OAuth 2.0 API Scopes document provides a full list of scopes that you might use to access Google APIs.

We recommend that your application request access to authorization scopes in context whenever possible. By requesting access to user data in context, via incremental authorization, you help users to more easily understand why your application needs the access it is requesting.
state Recommended. Specifies any string value that your application uses to maintain state between your authorization request and the authorization server's response. The server returns the exact value that you send as a name=value pair in the hash (#) fragment of the redirect_uri after the user consents to or denies your application's access request.

You can use this parameter for several purposes, such as directing the user to the correct resource in your application, sending nonces, and mitigating cross-site request forgery. Since your redirect_uri can be guessed, using a state value can increase your assurance that an incoming connection is the result of an authentication request. If you generate a random string or encode the hash of a cookie or another value that captures the client's state, you can validate the response to additionally ensure that the request and response originated in the same browser, providing protection against attacks such as cross-site request forgery. See the OpenID Connect documentation for an example of how to create and confirm a state token.
include_granted_scopes Optional. Enables applications to use incremental authorization to request access to additional scopes in context. If you set this parameter's value to true and the authorization request is granted, then the new access token will also cover any scopes to which the user previously granted the application access. See the incremental authorization section for examples.
login_hint Optional. If your application knows which user is trying to authenticate, it can use this parameter to provide a hint to the Google Authentication Server. The server uses the hint to simplify the login flow either by prefilling the email field in the sign-in form or by selecting the appropriate multi-login session.

Set the parameter value to an email address or sub identifier.
prompt Optional. A space-delimited, case-sensitive list of prompts to present the user. If you don't specify this parameter, the user will be prompted only the first time your app requests access. Possible values are:
none Do not display any authentication or consent screens. Must not be specified with other values.
consent Prompt the user for consent.
select_account Prompt the user to select an account.

Sample redirect to Google's authorization server

An example URL is shown below, with line breaks and spaces for readability.

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly&
 include_granted_scopes=true&
 state=state_parameter_passthrough_value&
 redirect_uri=http%3A%2F%2Foauth2.example.com%2Fcallback&
 response_type=token&
 client_id=client_id

After you create the request URL, redirect the user to it.

JavaScript sample code

The following JavaScript snippet shows how to initiate the authorization flow in JavaScript without using the Google APIs Client Library for JavaScript. Since this OAuth 2.0 endpoint does not support Cross-origin resource sharing (CORS), the snippet creates a form that opens the request to that endpoint.

/*
 * Create form to request access token from Google's OAuth 2.0 server.
 */
function oauthSignIn() {
  // Google's OAuth 2.0 endpoint for requesting an access token
  var oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';

  // Create <form> element to submit parameters to OAuth 2.0 endpoint.
  var form = document.createElement('form');
  form.setAttribute('method', 'GET'); // Send as a GET request.
  form.setAttribute('action', oauth2Endpoint);

  // Parameters to pass to OAuth 2.0 endpoint.
  var params = {'client_id': 'YOUR_CLIENT_ID',
                'redirect_uri': 'YOUR_REDIRECT_URI',
                'response_type': 'token',
                'scope': 'https://www.googleapis.com/auth/drive.metadata.readonly',
                'include_granted_scopes': 'true',
                'state': 'pass-through value'});

  // Add form parameters as hidden input values.
  for (var p in params) {
    var input = document.createElement('input');
    input.setAttribute('type', 'hidden');
    input.setAttribute('name', p);
    input.setAttribute('value', params[p]);
    form.appendChild(input);
  }

  // Add form to page and submit it to open the OAuth 2.0 endpoint.
  document.body.appendChild(form);
  form.submit();
}

Step 3: Google prompts user for consent

In this step, the user decides whether to grant your application the requested access. At this stage, Google displays a consent window that shows the name of your application and the Google API services that it is requesting permission to access with the user's authorization credentials. The user can then consent or refuse to grant access to your application.

Your application doesn't need to do anything at this stage as it waits for the response from Google's OAuth 2.0 server indicating whether the access was granted. That response is explained in the following step.

Step 4: Handle the OAuth 2.0 server response

JS Client Library

The JavaScript client library handles the response from Google's authorization server. If you set a listener to monitor changes in the current user's sign-in state, that function is called when the user grants the requested access to the application.

OAuth 2.0 Endpoints

The OAuth 2.0 server sends a response to the redirect_uri specified in your access token request.

If the user approves the request, then the response contains an access token. If the user does not approve the request, the response contains an error message. The access token or error message is returned on the hash fragment of the redirect URI, as shown below:

  • An authorization code response:

    https://oauth2.example.com/callback#access_token=4/P7q7W91&token_type=Bearer&expires_in=3600

    In addition to the access_token parameter, the query string also contains the token_type parameter, which is always set to Bearer, and the expires_in parameter, which specifies the lifetime of the token, in seconds. If the state parameter was specified in the access token request, its value is also included in the response.

  • An error response:

    https://oauth2.example.com/callback#error=access_denied

Note: Your application should ignore any additional, unrecognized fields included in the query string.

Sample OAuth 2.0 server response

You can test this flow by clicking on the following sample URL, which requests read-only access to view metadata for files in your Google Drive:

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly&
 include_granted_scopes=true&
 state=state_parameter_passthrough_value&
 redirect_uri=http%3A%2F%2Foauth2.example.com%2Fcallback&
 response_type=token&
 client_id=client_id

After completing the OAuth 2.0 flow, you will be redirected to http://localhost/oauth2callback. That URL will yield a 404 NOT FOUND error unless your local machine happens to serve a file at that address. The next step provides more detail about the information returned in the URI when the user is redirected back to your application.

The code snippet in step 5 shows how to parse the OAuth 2.0 server response and then validate the access token.

Step 5: Validate the user's token

JS Client Library

The JavaScript client library automatically validates the access token returned by Google's authorization server. This validation step ensures that your application is not vulnerable to the confused deputy problem.

OAuth 2.0 Endpoints

If the user has granted access to your application, you must explicitly validate the token returned in the hash fragment of the redirect_uri. By validating, or verifying, the token, you ensure that your application is not vulnerable to the confused deputy problem.

To validate the token, send a request to https://www.googleapis.com/oauth2/v3/tokeninfo and set the token as the access_token parameter's value. The following URL shows a sample request:

https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access_token>

Google's authorization server responds to the request with a JSON object that either describes the token or contains an error message.

  • If the token is valid, the JSON object includes the properties in the following table:
    Fields
    aud The application that is the intended user of the access token.
    Important: Before using the token, you need to verify that this field's value exactly matches your Client ID in the Google API Console. This verification ensures that your application is not vulnerable to the confused deputy problem.
    expires_in The number of seconds left before the token becomes invalid.
    scope A space-delimited list of scopes that the user granted access to. The list should match the scopes specified in your authorization request in step 1.
    userid This value lets you correlate profile information from multiple Google APIs. It is only present in the response if you included the profile scope in your request in step 1. The field value is an immutable identifier for the logged-in user that can be used to create and manage user sessions in your application.

    The identifier is the same regardless of which client ID is used to retrieve it. This enables multiple applications in the same organization to correlate profile information.

    A sample response is shown below:

    {
      "aud":"8819981768.apps.googleusercontent.com",
      "user_id":"123456789",
      "scope":"https://www.googleapis.com/auth/drive.metadata.readonly",
      "expires_in":436
    }
    
  • If the token has expired, been tampered with, or had its permissions revoked, Google's authorization server returns an error message in the JSON object. The error surfaces as a 400 error and a JSON body in the format shown below.
    {"error":"invalid_token"}
    By design, no additional information is given as to the reason for the failure.

    Note: In practice, a 400 error typically indicates that the access token request URL was malformed, often due to improper URL escaping.

The JavaScript snippet below parses the response from Google's authorization server and then validates the access token. If the token is valid, the code stores it in the browser's local storage. You could modify the snippet to also send the token to your server as a means of making the token available to other API clients.

var queryString = location.hash.substring(1);

// Parse the query string to extract access token and other parameters.
// This code is useful if you set a value for the 'state' parameter when
// redirecting the user to the OAuth 2.0 server, but otherwise isn't needed.
var params = {};
var regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(queryString)) {
  params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
  // Try to exchange the param values for an access token.
  exchangeOAuth2Token(params);
}

/* Validate the access token received on the query string. */
function exchangeOAuth2Token(params) {
  var oauth2Endpoint = 'https://www.googleapis.com/oauth2/v3/tokeninfo';
  if (params['access_token']) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', oauth2Endpoint + '?access_token=' + params['access_token']);
    xhr.onreadystatechange = function (e) {
      var response = JSON.parse(xhr.response);
      // Verify that the 'aud' property in the response matches YOUR_CLIENT_ID.
      if (xhr.readyState == 4 &&
          xhr.status == 200 &&
          response['aud'] &&
          response['aud'] == YOUR_CLIENT_ID) {
        localStorage.setItem('oauth2-test-params', JSON.stringify(params) );
      } else if (xhr.readyState == 4) {
        console.log('There was an error processing the token, another ' +
                    'response was returned, or the token was invalid.')
      }
    };
    xhr.send(null);
  }
}

Calling Google APIs

JS Client Library

After your application obtains an access token, you can use the JavaScript client library to make API requests on the user's behalf. The client library manages the access token for you, and you do not need to do anything special to send it in the request.

The client library supports two ways to call API methods. If you have loaded a discovery document, the API will define method-specific functions for you. You can also use the gapi.client.request function to call an API method. The following two snippets demonstrate these options for the Drive API's about.get method.

// Example 1: Use method-specific function
var request = gapi.client.drive.about.get({'fields': 'user'});

// Execute the API request.
request.execute(function(response) {
  console.log(response);
});


// Example 2: Use gapi.client.request(args) function
var request = gapi.client.request({
  'method': 'GET',
  'path': '/drive/v3/about',
  'params': {'fields': 'user'}
});
// Execute the API request.
request.execute(function(response) {
  console.log(response);
});

OAuth 2.0 Endpoints

After your application obtains an access token, you can use the token to make calls to a Google API on behalf of a given user account or service account. To do this, include the access token in a request to the API by including either an access_token query parameter or an Authorization: Bearer HTTP header. When possible, the HTTP header is preferable, because query strings tend to be visible in server logs. In most cases you can use a client library to set up your calls to Google APIs (for example, when calling the Drive Files API).

You can try out all the Google APIs and view their scopes at the OAuth 2.0 Playground.

HTTP GET examples

A call to the drive.files endpoint (the Drive Files API) using the Authorization: Bearer HTTP header might look like the following. Note that you need to specify your own access token:

GET /drive/v2/files HTTP/1.1
Authorization: Bearer <access_token>
Host: www.googleapis.com/

Here is a call to the same API for the authenticated user using the access_token query string parameter:

GET https://www.googleapis.com/drive/v2/files?access_token=<access_token>

curl examples

You can test these commands with the curl command-line application. Here's an example that uses the HTTP header option (preferred):

curl -H "Authorization: Bearer <access_token>" https://www.googleapis.com/drive/v2/files

Or, alternatively, the query string parameter option:

curl https://www.googleapis.com/drive/v2/files?access_token=<access_token>

JavaScript sample code

The code snippet below demonstrates how to use CORS (Cross-origin resource sharing) to send a request to a Google API. This example does not use the Google APIs Client Library for JavaScript. However, even if you are not using the client library, the CORS support guide in that library's documentation will likely help you to better understand these requests.

In this code snippet, the access_token variable represents the token you have obtained to make API requests on the authorized user's behalf. The complete example demonstrates how to store that token in the browser's local storage and retrieve it when making an API request.

var xhr = new XMLHttpRequest();
xhr.open('GET',
    'https://www.googleapis.com/drive/v3/about?fields=user&' +
    'access_token=' + params['access_token']);
xhr.onreadystatechange = function (e) {
  console.log(xhr.response);
};
xhr.send(null);

Complete example

JS Client Library

Sample code demo

This section contains a working demo of the code sample that follows to demonstrate how the code behaves in an actual app. After you authorize the app, it will be listed among the apps connected to your Google Account. The app is named OAuth 2.0 Demo for Google API Docs. Similarly, if you revoke access and refresh that page, that app will no longer be listed.

Note that this app requests access to the https://www.googleapis.com/auth/drive.metadata.readonly scope. The access is requested only to demonstrate how to initiate the OAuth 2.0 flow in a JavaScript application. This app does not make any API requests.

JavaScript sample code

As shown above, this code sample is for a page (an app) that loads the Google APIs Client Library for JavaScript and initiates the OAuth 2.0 flow. The page displays either:

  • One button that lets the user sign in to the app. If the user has not previously authorized the app, then the app launches the OAuth 2.0 flow.

  • Two buttons that allow the user to either sign out of the app or to revoke access previously granted to the app. If you sign out of an app, you have not revoked access granted to the app. You will need to sign in again before the app can make other authorized requests on your behalf, but you will not have to grant access again the next time you use the app. However, if you revoke access, then you do need to grant access again.

You can also revoke access to the app through the Permissions page for your Google Account. The app is listed as OAuth 2.0 Demo for Google API Docs.

<script>
  var GoogleAuth;
  var SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly';
  function handleClientLoad() {
    // Load the API's client and auth2 modules.
    // Call the initClient function after the modules load.
    gapi.load('client:auth2', initClient);
  }

  function initClient() {
    // Retrieve the discovery document for version 3 of Google Drive API.
    // In practice, your app can retrieve one or more discovery documents.
    var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';

    // Initialize the gapi.client object, which app uses to make API requests.
    // Get API key and client ID from API Console.
    // 'scope' field specifies space-delimited list of access scopes.
    gapi.client.init({
        'apiKey': 'YOUR_API_KEY',
        'discoveryDocs': [discoveryUrl],
        'clientId': 'YOUR_CLIENT_ID',
        'scope': SCOPE
    }).then(function () {
      GoogleAuth = gapi.auth2.getAuthInstance();

      // Listen for sign-in state changes.
      GoogleAuth.isSignedIn.listen(updateSigninStatus);

      // Handle initial sign-in state. (Determine if user is already signed in.)
      var user = GoogleAuth.currentUser.get();
      setSigninStatus();

      // Call handleAuthClick function when user clicks on
      //      "Sign In/Authorize" button.
      $('#sign-in-or-out-button').click(function() {
        handleAuthClick();
      }); 
      $('#revoke-access-button').click(function() {
        revokeAccess();
      }); 
    });
  }

  function handleAuthClick() {
    if (GoogleAuth.isSignedIn.get()) {
      // User is authorized and has clicked 'Sign out' button.
      GoogleAuth.signOut();
    } else {
      // User is not signed in. Start Google auth flow.
      GoogleAuth.signIn();
    }
  }

  function revokeAccess() {
    GoogleAuth.disconnect();
  }

  function setSigninStatus(isSignedIn) {
    var user = GoogleAuth.currentUser.get();
    var isAuthorized = user.hasGrantedScopes(SCOPE);
    if (isAuthorized) {
      $('#sign-in-or-out-button').html('Sign out');
      $('#revoke-access-button').css('display', 'inline-block');
      $('#auth-status').html('You are currently signed in and have granted ' +
          'access to this app.');
    } else {
      $('#sign-in-or-out-button').html('Sign In/Authorize');
      $('#revoke-access-button').css('display', 'none');
      $('#auth-status').html('You have not authorized this app or you are ' +
          'signed out.');
    }
  }

  function updateSigninStatus(isSignedIn) {
    setSigninStatus();
  }
</script>

<button id="sign-in-or-out-button"
        style="margin-left: 25px">Sign In/Authorize</button>
<button id="revoke-access-button"
        style="display: none; margin-left: 25px">Revoke access</button>

<div id="auth-status" style="display: inline; padding-left: 25px"></div><hr>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script async defer src="https://apis.google.com/js/api.js" 
        onload="this.onload=function(){};handleClientLoad()" 
        onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

OAuth 2.0 Endpoints

This code sample demonstrates how to complete the OAuth 2.0 flow in JavaScript without using the Google APIs Client Library for JavaScript. The code is for an HTML page that displays a button to try an API request. If you click the button, the code checks to see whether the page has stored an API access token in your browser's local storage. If so, it executes the API request. Otherwise, it initiates the OAuth 2.0 flow.

For the OAuth 2.0 flow, the page follows these steps:

  1. It directs the user to Google's OAuth 2.0 server, which requests access to the https://www.googleapis.com/auth/drive.metadata.readonly scope.
  2. After granting (or denying) access, the user is redirected to the original page, which parses the access token from the query string.
  3. The page validates the access token and, if it is valid, executes the sample API request. The API request calls the Drive API's about.get method to retrieve information about the authorized user's Google Drive account.
  4. If the request executes successfully, the API response is logged in the browser's debugging console.

You can revoke access to the app through the Permissions page for your Google Account. The app will be listed as OAuth 2.0 Demo for Google API Docs.

To run this code locally, you need to set values for the YOUR_CLIENT_ID and REDIRECT_URI variables that correspond to your authorization credentials. The REDIRECT_URI should be the same URL where the page is being served. Your project in the Google API Console must also have enabled the appropriate API for this request.

<html><head></head><body>
<script>
  var YOUR_CLIENT_ID = 'REPLACE_THIS_VALUE';
  var YOUR_REDIRECT_URI = 'REPLACE_THIS_VALUE';
  var queryString = location.hash.substring(1);

  // Parse query string to see if page request is coming from OAuth 2.0 server.
  var params = {};
  var regex = /([^&=]+)=([^&]*)/g, m;
  while (m = regex.exec(queryString)) {
    params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    // Try to exchange the param values for an access token.
    exchangeOAuth2Token(params);
  }

  // If there's an access token, try an API request.
  // Otherwise, start OAuth 2.0 flow.
  function trySampleRequest() {
    var params = JSON.parse(localStorage.getItem('oauth2-test-params'));
    if (params && params['access_token']) {
      var xhr = new XMLHttpRequest();
      xhr.open('GET',
          'https://www.googleapis.com/drive/v3/about?fields=user&' +
          'access_token=' + params['access_token']);
      xhr.onreadystatechange = function (e) {
        console.log(xhr.response);
      };
      xhr.send(null);
    } else {
      oauth2SignIn();
    }
  }

  /*
   * Create form to request access token from Google's OAuth 2.0 server.
   */
  function oauth2SignIn() {
    // Google's OAuth 2.0 endpoint for requesting an access token
    var oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';

    // Create element to open OAuth 2.0 endpoint in new window.
    var form = document.createElement('form');
    form.setAttribute('method', 'GET'); // Send as a GET request.
    form.setAttribute('action', oauth2Endpoint);

    // Parameters to pass to OAuth 2.0 endpoint.
    var params = {'client_id': YOUR_CLIENT_ID,
                  'redirect_uri': YOUR_REDIRECT_URI,
                  'scope': 'https://www.googleapis.com/auth/drive.metadata.readonly',
                  'state': 'try_sample_request',
                  'include_granted_scopes': 'true',
                  'response_type': 'token'};

    // Add form parameters as hidden input values.
    for (var p in params) {
      var input = document.createElement('input');
      input.setAttribute('type', 'hidden');
      input.setAttribute('name', p);
      input.setAttribute('value', params[p]);
      form.appendChild(input);
    }

    // Add form to page and submit it to open the OAuth 2.0 endpoint.
    document.body.appendChild(form);
    form.submit();
  }

  /* Verify the access token received on the query string. */
  function exchangeOAuth2Token(params) {
    var oauth2Endpoint = 'https://www.googleapis.com/oauth2/v3/tokeninfo';
    if (params['access_token']) {
      var xhr = new XMLHttpRequest();
      xhr.open('POST', oauth2Endpoint + '?access_token=' + params['access_token']);
      xhr.onreadystatechange = function (e) {
        var response = JSON.parse(xhr.response);
        // When request is finished, verify that the 'aud' property in the
        // response matches YOUR_CLIENT_ID.
        if (xhr.readyState == 4 &&
            xhr.status == 200 &&
            response['aud'] &&
            response['aud'] == YOUR_CLIENT_ID) {
          // Store granted scopes in local storage to facilitate
          // incremental authorization.
          params['scope'] = response['scope'];
          localStorage.setItem('oauth2-test-params', JSON.stringify(params) );
          if (params['state'] == 'try_sample_request') {
            trySampleRequest();
          }
        } else if (xhr.readyState == 4) {
          console.log('There was an error processing the token, another ' +
                      'response was returned, or the token was invalid.')
        }
      };
      xhr.send(null);
    }
  }
</script>

<button onclick="trySampleRequest();">Try sample request</button>
</body></html>

Incremental authorization

In the OAuth 2.0 protocol, your app requests authorization to access resources, which are identified by scopes. It is considered a best user-experience practice to request authorization for resources at the time you need them. To enable that practice, Google's authorization server supports incremental authorization. This feature lets you request scopes as they are needed and, if the user grants permission, add those scopes to your existing access token for that user.

For example, an app that lets people sample music tracks and create mixes might need very few resources at sign-in time, perhaps nothing more than the name of the person signing in. However, saving a completed mix would require access to their Google Drive. Most people would find it natural if they only were asked for access to their Google Drive at the time the app actually needed it.

In this case, at sign-in time the app might request the profile scope to perform basic sign-in, and then later request the https://www.googleapis.com/auth/drive.file scope at the time of the first request to save a mix.

The following rules apply to an access token obtained from an incremental authorization:

  • The token can be used to access resources corresponding to any of the scopes rolled into the new, combined authorization.
  • When you use the refresh token for the combined authorization to obtain an access token, the access token represents the combined authorization and can be used for any of its scopes.
  • The combined authorization includes all scopes that the user granted to the API project even if the grants were requested from different clients. For example, if a user granted access to one scope using an application's desktop client and then granted another scope to the same application via a mobile client, the combined authorization would include both scopes.
  • If you revoke a token that represents a combined authorization, access to all of that authorization's scopes on behalf of the associated user are revoked simultaneously.

The code samples below show how to add scopes to an existing access token. This approach allows your app to avoid having to manage multiple access tokens.

JS Client Library

To add scopes to an existing access token, call the GoogleUser.grant(options) method. The options object identifies the additional scopes to which you want to grant access.

// Space-separated list of additional scope(s) you are requesting access to.
// This code adds read-only access to the user's calendars via the Calendar API.
var NEW_SCOPES = 'https://www.googleapis.com/auth/calendar.readonly';

// Retrieve the GoogleUser object for the current user.
var GoogleUser = GoogleAuth.currentUser.get();
GoogleUser.grant({'scope': NEW_SCOPES});

OAuth 2.0 Endpoints

To add scopes to an existing access token, include the include_granted_scopes parameter in your request to Google's OAuth 2.0 server.

The following code snippet demonstrates how to do that. The snippet assumes that you have stored the scopes for which your access token is valid in the browser's local storage. (The complete example code stores a list of scopes for which the access token is valid by setting the oauth2-test-params.scope property in the browser's local storage.)

The snippet compares the scopes for which the access token is valid to the scope you want to use for a particular query. If the access token does not cover that scope, the OAuth 2.0 flow starts. Here, the oauth2SignIn function is the same as the one that was provided in step 2 (and that is provided later in the complete example).

var SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly';
var params = JSON.parse(localStorage.getItem('oauth2-test-params'));

var current_scope_granted = false;
if (params.hasOwnProperty('scope')) {
  var scopes = params['scope'].split(' ');
  for (var s = 0; s < scopes.length; s++) {
    if (SCOPE == scopes[s]) {
      current_scope_granted = true;
    }
  }
}

if (!current_scope_granted) {
  oauth2SignIn(); // This function is defined elsewhere in this document.
} else {
  // Since you already have access, you can proceed with the API request.
}

Revoking a token

In some cases a user may wish to revoke access given to an application. A user can revoke access by visiting Account Settings. It is also possible for an application to programmatically revoke the access given to it. Programmatic revocation is important in instances where a user unsubscribes or removes an application. In other words, part of the removal process can include an API request to ensure the permissions granted to the application are removed.

JS Client Library

To programmatically revoke a token, call GoogleAuth.disconnect():

GoogleAuth.disconnect();

OAuth 2.0 Endpoints

To programmatically revoke a token, your application makes a request to https://accounts.google.com/o/oauth2/revoke and includes the token as a parameter:

curl -H "Content-type:application/x-www-form-urlencoded" \
        https://accounts.google.com/o/oauth2/revoke?token={token}

The token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.

Note: Google's OAuth 2.0 endpoint for revoking tokens supports JSONP and form submissions. It does not support Cross-origin Resource Sharing (CORS).

If the revocation is successfully processed, then the status code of the response is 200. For error conditions, a status code 400 is returned along with an error code.

The following JavaScript snippet shows how to revoke a token in JavaScript without using the Google APIs Client Library for JavaScript. Since the Google's OAuth 2.0 endpoint for revoking tokens does not support Cross-origin Resource Sharing (CORS), the code creates a form and submits the form to the endpoint rather than using the XMLHttpRequest() method to post the request.

function revokeAccess(accessToken) {
  // Google's OAuth 2.0 endpoint for revoking access tokens.
  var revokeTokenEndpoint = 'https://accounts.google.com/o/oauth2/revoke';

  // Create <form> element to use to POST data to the OAuth 2.0 endpoint.
  var form = document.createElement('form');
  form.setAttribute('method', 'post');
  form.setAttribute('action', revokeTokenEndpoint);

  // Add access token to the form so it is set as value of 'token' parameter.
  // This corresponds to the sample curl request, where the URL is:
  //      https://accounts.google.com/o/oauth2/revoke?token={token}
  var tokenField = document.createElement('input');
  tokenField.setAttribute('type', 'hidden');
  tokenField.setAttribute('name', 'token');
  tokenField.setAttribute('value', accessToken);
  form.appendChild(tokenField);

  // Add form to page and submit it to actually revoke the token.
  document.body.appendChild(form);
  form.submit();
}