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.

Note: Given the security implications
of getting the implementation correct, we strongly encourage you to use
OAuth 2.0 libraries when interacting with Google's OAuth 2.0 endpoints. It
is a best practice to use well-debugged code provided by others, and it
will help you protect yourself and your users. See the
JS Client Library tabs in this document for examples that show how
to authorize users with the Google APIs Client Library for JavaScript.

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:

Select the project associated with your application. Create a project if
you do not have one already.

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.

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.

If your public application uses scopes that permit access to
certain user data, it must pass review. If you see unverified
app on the screen when testing your application, you must submit a
verification request to remove it. Find out more about
unverified apps
and get answers to
frequently asked questions about app verification in the Help Center.

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

It creates the redirect URL for Google's authorization server and
provides a method to direct the user to that URL.

It handles the redirect from that server back to your application.

It validates the access token returned by the authorization server.

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.)

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.

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
authorized redirect URIs for the OAuth 2.0 client, which you configured in
the API Console. If this value doesn't match an authorized URI,
you will get a 'redirect_uri_mismatch' error.
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, which is equivalent to the user's Google ID.

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.

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.

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:

In addition to the access_token parameter, the
fragment 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:

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.

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.

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).

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.

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.

[This section requires a browser that supports JavaScript and iframes.]

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.

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:

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.

After granting (or denying) access, the user is redirected to the original
page, which parses the access token from the fragment string.

The page uses the access token to make 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.

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. The value must exactly match one of the authorized
redirect URIs for the OAuth 2.0 client, which you configured in the API
Console. If this value doesn't match an authorized URI, you will get a
'redirect_uri_mismatch' error. Your project in the Google API Console must also
have enabled the appropriate API for this request.

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.

OAuth 2.0 Endpoints

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).

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.

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.