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:
- Open the Library page in the API Console.
- 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.
Open the Credentials page in the API Console.
Click Create credentials > OAuth client ID.
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 LIBRARYOAUTH 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 LIBRARYOAUTH 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 : 必須
- The client ID for your application. You can find this value in the API Console.
- redirect_uri : 必須
- ユーザが認証を行った後、API サーバがリダイレクトする場所を指定。この値は API Console で指定したリダイレクトURLのどれかと正確に一致している必要がある。http or https, case, ('/') まですべて一致。
- response_type : 必須
- JavaScript アプリケーションでは token を指定する。この指示により Google 認証サーバは アクセストークンを name=value のペアで、ハッシュ (#) fragment をつけて、返すようになる。
- scope : 必須
- 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 LIBRARYOAUTH 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:
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:
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 LIBRARYOAUTH 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.
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);
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 LIBRARYOAUTH 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 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 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:
You can test these commands with the curl command-line application. Here's an example that uses the HTTP header option (preferred):
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 LIBRARYOAUTH 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 query string.
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.
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 LIBRARYOAUTH 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 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.
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();
}
Note: Following a successful revocation response, it might take some time before the revocation has full effect.
最終更新:2017年03月26日 12:29