This OAuth 2.0 flow is designed to enable JavaScript-based web applications to send authorized Google API requests. These applications cannot maintain state over time, meaning that the application sends API requests while the user is present at the application. This flow assumes that the application cannot store confidential information.
Important: You need to obtain authorization credentials in the Google API Console to be able to use OAuth 2.0 authorization.
This document contains the following sections:
-
The Obtaining OAuth 2.0 access tokens section explains how to obtain OAuth 2.0 access tokens for client-side web applications. The Google Accounts Authentication and Authorization documentation also provides complete details for implementing OAuth 2.0 in different types of applications.
-
The Making an authorized API request section explains how to use the OAuth 2.0 tokens that your application obtains to make authorized API requests on a user's behalf.
-
The Client libraries section describes client library support for OAuth 2.0.
Obtaining OAuth 2.0 access tokens
This flow has the following steps:
-
Request an access token
Note: Requests to Google's authorization server must use
https
instead ofhttp
because the server is only accessible over SSL (HTTPs) and refuses HTTP connections.When a user first tries to perform an action that requires API authentication, you need to direct the user to Google's authorization server at
https://accounts.google.com/o/oauth2/auth
. The table below identifies the request parameters that you need to (or can) include in the URL. Note that the request URI that you construct must contain properly URL-escaped parameter values.Parameters client_id
Required. The OAuth 2.0 client ID for your application. You can find this value in the API Console. redirect_uri
Required. A registered redirect_uri
for your client ID. Register valid redirect URIs for your application in the API Console.response_type
Required. Determines whether the Google OAuth 2.0 endpoint returns an authorization code. JavaScript applications need to set the parameter's value to token
. This instructs the Google Authorization Server to return the access token as aname=value
pair in the hash (#
) fragment of the redirect URI that the server returns.scope
Required. A space-delimited list of scopes that identify the resources that your application could access on the user's behalf. These values determine which permissions are listed on the consent page that Google displays to the user.
The YouTube Data API supports the following scopes:
Scopes https://www.googleapis.com/auth/youtube.force-ssl Manage your YouTube account. This scope requires communication with the API server to happen over an SSL connection. https://www.googleapis.com/auth/youtube Manage your YouTube account. This scope is functionally identical to the youtube.force-ssl
scope listed above because the YouTube API server is only available via an HTTPS endpoint. As a result, even though this scope does not require an SSL connection, there is actually no other way to make an API request.https://www.googleapis.com/auth/youtube.readonly View your YouTube account. https://www.googleapis.com/auth/youtube.upload Upload YouTube videos and manage your YouTube videos. https://www.googleapis.com/auth/youtubepartner-channel-audit Retrieve the auditDetails
part in achannel
resource.approval_prompt
Optional. This parameter indicates whether the user should be prompted to grant account access to your application each time she tries to complete a particular action. The default value is auto
, which indicates that a user would only need to grant access the first time she tried to access a protected resource.
Set the parameter value toforce
to direct the user to a consent page even if she has already granted access to your application for a particular set of scopes.state
Optional. A string that your application uses to maintain state between the request and redirect response. The exact value that you send is returned as a name=value
pair in the hash (#
) fragment of theredirect_uri
after the user consents to or denies your application's access request. You could 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.login_hint
Optional. If your application knows which user is trying to authenticate, it can use this parameter to provide a hint to Google's Authentication Server. The server uses the hint to simplify the login flow by either prefilling the email field in the sign-in form or selecting the appropriate multi-login session. The sample URL below shows a Google's authorization server URI that requests permission for an application to submit API requests on the user's behalf. Note that parameter values must be properly URL-escaped.
https://accounts.google.com/o/oauth2/auth?
client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com&
redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
scope=https://www.googleapis.com/auth/youtube&
response_type=token -
User consent decision
In this step, the user decides whether to grant your application the ability to make API requests that are authorized as the user. Google's authorization server displays 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.
You can test this flow by clicking on the sample URL in the previous step. You can also see how the user's response appears in the redirect URI by placing a file on your server at
http://localhost/oauth2callback
. (See the next step for more details.) -
Handle response from Google
After the user consents or refuses to grant access to your application, Google redirects the user to the
redirect_uri
that you specified in step 1.-
If the user granted access to your application, Google appends a short-lived access token in the hash fragment of the redirect URI as shown in the sample URI below. The response also includes the
expires_in
andtoken_type
parameters. These parameters describe the lifetime of the token in seconds and the kind of token that is being returned, respectively. Finally, the response includes thestate
parameter if astate
parameter was included in the original request to the authorization server.http://localhost/oauth2callback#access_token=1/QbIbRMWW&token_type=Bearer&expires_in=3600
Note: Your application should also allow other parameters to be included in the response's hash fragment. The paragraph above describes the minimum set of name-value pairs returned in the
redirect_uri
.JavaScript code running on your page can capture the access token from the
window.location.hash
value and either store the token in a cookie orPOST
it to a server. -
If the user refused to grant access to your application, Google includes the
access_denied
error message in the hash fragment of theredirect_uri
:http://localhost/oauth2callback#error=access_denied
-
-
Validate the user's token
Assuming the user has granted access to your application, you need to explicitly validate the token returned in 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/v1/tokeninfo
and set the token as theaccess_token
parameter's value. That URL accepts and returns information about the token, including the application that the token was issued to, the user associated with the token, the scopes that the user granted access to, and the time before the token expires.The sample URL below demonstrates where you would send a token validation request:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ACCESS_TOKEN
-
Process the token validation response
In response to a token validation request, the Google authorization server returns a JSON object that either describes the token or contains an error message.
-
If the token is valid, the JSON object includes the following properties:
Fields audience
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 yourClient 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 https://www.googleapis.com/auth/userinfo.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.A sample response is shown below:
{ "audience":"8819981768.apps.googleusercontent.com", "user_id":"123456789", "scope":"https://www.googleapis.com/auth/youtube", "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.
-
Making an authorized API request
After obtaining an access token for a user, your application can use that token to submit
authorized API requests on that user's behalf. Specify the access token as the value of the
Authorization: Bearer
HTTP request header
GET /youtube/v3/channels?part=id&mine=true HTTP/1.1 Host: www.googleapis.com Authorization: Bearer ACCESS_TOKEN ...
You can test this using cURL with the following command:
curl -H "Authorization: Bearer ACCESS_TOKEN" https://www.googleapis.com/youtube/v3/channels?part=id&mine=true
The API returns an HTTP 401 response code (Unauthorized) if you submit a request to access a protected resource with an access token that is expired, bogus, improperly scoped, or invalid for some other reason.
If the API returns an HTTP 403 response code, then your application may not be registered. Many APIs set a query-volume limit of 0
for unregistered applications and return a 403 response code when the query-volume limit is exceeded.
The following section explains how to refresh an access token.
Refreshing an access token
Access tokens periodically expire and, when that happens, need to be refreshed. When an access token expires or at any other time, your application may be able to use a refresh token to obtain a new, valid access token. Server-side web applications, installed applications, and devices all obtain refresh tokens during the authorization process.
To refresh an access token, your application sends a POST
request to Google's authorization server that specifies your client ID, your client secret, and the refresh token for the user. The request also sets the grant_type
parameter value to refresh_token
. The following example demonstrates this request:
POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-Type: application/x-www-form-urlencoded client_id=21302922996.apps.googleusercontent.com& client_secret=XTHhXh1SlUNgvyWGwDk1EjXB& refresh_token=1/6BMfW9j53gdGImsixUH6kU5RsR4zwI9lUVX-tqf8JXQ& grant_type=refresh_token
The authorization server returns a JSON object that contains a new access token:
{ "access_token":"1/fFAGRNJru1FTz70BzhT3Zg", "expires_in":3920, "token_type":"Bearer" }
Note that there are limits on the number of refresh tokens that will be issued; one limit per client/user combination, and another per user across all clients. You should save refresh tokens in long-term storage and continue to use them as long as they remain valid. If your application requests too many refresh tokens, it may run into these limits, in which case older refresh tokens will stop working.
Revoking a Token
There are two ways to revoke an access token:
-
A user can revoke access given to an application by visiting the following URL and explicitly revoking access:
https://accounts.google.com/b/0/IssuedAuthSubTokens
The following steps explain how to reach this page:
- Click on the user's picture in the Google sandbar and then click the Account link or navigate in some other way to the Account Overview page for the user's Google Account.
- Follow the link to the Security settings page.
- Click the button to manage access to connected applications and websites that can access and use details from the user's Google Account.
-
An application can programmatically revoke its own access. This type of revocation is important in instances where a user unsubscribes or removes an application, in which an API request to remove the permissions granted to the application should be a part of the removal process.
To programmatically revoke a token, your application sends a request to
https://accounts.google.com/o/oauth2/revoke
and includes the token as a parameter:curl https://accounts.google.com/o/oauth2/revoke?token={token}
The specified 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 is also revoked.
If the revocation succeeds, the response's status code is
200
. If an error occurs, the response's status code is400
and the response also contains an error code.
Client libraries
Note: If you are planning to provide a sign-in with Google feature, we recommend using Google Sign-in, which provides an OAuth 2.0 authentication mechanism.
You can use the client libraries listed below to implement OAuth 2.0 in your application. We recommend using a client library rather than writing your own code. Using these standard client libraries is important for the safety and security of your users and your application.
- Google APIs Client Library for Java
- Google APIs Client Library for JavaScript
- Google APIs Client Library for Python
- Google APIs Client Library for .NET
- Google APIs Client Library for Ruby
- Google APIs Client Library for PHP
- OAuth 2.0 Library for Google Web Toolkit
- Google Toolbox for Mac OAuth 2.0 Controllers
You can also follow the instructions in the Making an authorized API request section to modify your code to properly set the OAuth 2.0 token values.