Google Accounts Authentication and Authorization

Using OAuth 2.0 for Web Server Applications

The Google OAuth 2.0 endpoint supports web server applications that use languages and frameworks such as PHP, Java, Python, Ruby, and ASP.NET. These applications might access a Google API while the user is present at the application or after the user has left the application. This flow requires that the application can keep a secret.

This document describes how to use OAuth 2.0 when accessing a Google API from a web server application.

Contents

  1. Overview
  2. Forming the URL
  3. Handling the response
  4. Calling a Google API
  5. Incremental authorization
  6. Offline access
  7. Revoking a token
  8. Client libraries

Overview

The authorization sequence begins when your application redirects a browser to a Google URL; the URL includes query parameters that indicate the type of access being requested. As in other scenarios, Google handles user authentication, session selection, and user consent. The result is an authorization code, which Google returns to your application in a query string.

After receiving the authorization code, your application can exchange the code (along with a client ID and client secret) for an access token and, in some cases, a refresh token.

The application can then use the access token to access a Google API.

If a refresh token is present in the authorization code exchange, then it can be used to obtain new access tokens at any time. This is called offline access, because the user does not have to be present at the browser when the application obtains a new access token.

Your application sends a token request to the Google Authorization Server, receives an authorization code, 
exchanges the code for a token, and uses the token to call a Google API endpoint.

Forming the URL

The URL used when authenticating a user is https://accounts.google.com/o/oauth2/auth. This endpoint is accessible over SSL, and HTTP connections are refused.

Endpoint Description
https://accounts.google.com/o/oauth2/auth This endpoint is the target of the initial request. It handles active session lookup, authenticating the user, and user consent. The result of requests to this endpoint include access tokens, refresh tokens, and authorization codes.

The set of query string parameters supported by the Google Authorization Server for web server applications are:

Parameter Values Description
response_type code Determines whether the Google OAuth 2.0 endpoint returns an authorization code. Web server applications should use code.
client_id The client ID you obtain from the Developers Console. Identifies the client that is making the request. The value passed in this parameter must exactly match the value shown in the Google Developers Console.
redirect_uri One of the redirect_uri values listed for this project in the Developers Console. Determines where the response is sent. The value of this parameter must exactly match one of the values listed for this project in the Google Developers Console (including the http or https scheme, case, and trailing '/').
scope Space-delimited set of permissions that the application requests. Identifies the Google API access that your application is requesting. The values passed in this parameter inform the consent screen that is shown to the user. There is an inverse relationship between the number of permissions requested and the likelihood of obtaining user consent. For information about available login scopes, see Login scopes. To see the available scopes for all Google APIs, visit the APIs Explorer. It is generally a best practice to request scopes incrementally, at the time access is required, rather than up front. For example, an app that wants to support purchases should not request Google Wallet access until the user presses the “buy” button; see Incremental authorization.
state Any string Provides any state that might be useful to your application upon receipt of the response. The Google Authorization Server roundtrips this parameter, so your application receives the same value it sent. Possible uses include redirecting the user to the correct resource in your site, nonces, and cross-site-request-forgery mitigations.
access_type online or offline Indicates whether your application needs to access a Google API when the user is not present at the browser. This parameter defaults to online. If your application needs to refresh access tokens when the user is not present at the browser, then use offline. This will result in your application obtaining a refresh token the first time your application exchanges an authorization code for a user.
approval_prompt force or auto Indicates whether the user should be re-prompted for consent. The default is auto, so a given user should only see the consent page for a given set of scopes the first time through the sequence. If the value is force, then the user sees a consent page even if they previously gave consent to your application for a given set of scopes.
login_hint email address or sub identifier When your application knows which user it is trying to authenticate, it can provide this parameter as a hint to the Authentication Server. Passing this hint will either pre-fill the email box on the sign-in form or select the proper multi-login session, thereby simplifying the login flow.
include_granted_scopes true or false If this is provided with the value true, and the authorization request is granted, the authorization will include any previous authorizations granted to this user/application combination for other scopes; see Incremental Authorization.


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

https://accounts.google.com/o/oauth2/auth?
 scope=email%20profile&
 state=%2Fprofile&
 redirect_uri=https%3A%2F%2Foauth2-login-demo.appspot.com%2Fcode&
 response_type=code&
 client_id=812741506391.apps.googleusercontent.com&
 approval_prompt=force

Handling the response

The response will be sent to the redirect_uri as specified in the request URL. If the user approves the access request, then the response contains an authorization code and the state parameter (if included in the request). If the user does not approve the request, the response contains an error message. All responses are returned to the web server on the query string, as shown below:

An error response:

https://oauth2-login-demo.appspot.com/code?error=access_denied&state=/profile

An authorization code response:

https://oauth2-login-demo.appspot.com/code?state=/profile&code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7

After the web server receives the authorization code, it may exchange the authorization code for an access token and a refresh token. This request is an HTTPS POST, and includes the following parameters:

Field Description
code The authorization code returned from the initial request.
client_id The client ID obtained from the Developers Console.
client_secret The client secret obtained from the Developers Console.
redirect_uri One of the redirect URIs listed for this project in the Developers Console.
grant_type As defined in the OAuth 2.0 specification, this field must contain a value of authorization_code.

The actual request might look like the following:

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code

A successful response to this request contains the following fields:

Field Description
access_token The token that can be sent to a Google API.
refresh_token A token that may be used to obtain a new access token. Refresh tokens are valid until the user revokes access. This field is only present if access_type=offline is included in the authorization code request.
expires_in The remaining lifetime of the access token.
token_type Identifies the type of token returned. At this time, this field will always have the value Bearer.

A successful response is returned as a JSON array, similar to the following:

{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer"
}

Note: Other fields may be included in the response, and your application should not treat this as an error. The set shown above is the minimum set.

Calling a Google API

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. 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, it is preferable to use the HTTP Header, since 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 People API).

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

Examples

A call to the people.get endpoint (the People API) using the access_token query string parameter might look like the following:

GET https://www.googleapis.com/plus/v1/people/{userId}?access_token=1/fFBGRNJru1FQd44AzqT3Zg

Here is a call to the same API for the authenticated user (me) using the access_token Authorization: Bearer HTTP header:

GET /plus/v1/people/me HTTP/1.1
Authorization: Bearer 1/fFBGRNJru1FQd44AzqT3Zg
Host: googleapis.com

You can try either out in the CURL command line application. Here's an example of the query string parameter option:

curl https://www.googleapis.com/plus/v1/people/me?access_token=1/fFBGRNJru1FQd44AzqT3Zg

And the HTTP header option:

curl -H "Authorization: Bearer 1/fFBGRNJru1FQd44AzqT3Zg" https://www.googleapis.com/plus/v1/people/me

Incremental authorization

In the OAuth protocol, your app requests authorization to access resources which are identified by scopes, and assuming the user is authenticated and approves, your app receives short-lived access tokens which let it access those resources, and (optionally) refresh tokens to allow long-term access.

It is considered a best user-experience practice to request authorization for resources at the time you need them. 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 scope https://www.googleapis.com/auth/plus.login to perform a basic social-login function, and then later request the scope https://www.googleapis.com/auth/drive.file at the time of the first request to save a mix.

Using the procedures described in Using OAuth 2.0 for Login and Using OAuth 2.0 to Access Google APIs would normally result in your app having to manage two different access tokens. If you wish to avoid this complexity, you may add an extra parameter to the Authentication URI that you send to https://accounts.google.com/o/oauth2/auth as the first step of any OAuth 2.0 flow. The parameter is include_granted_scopes and the allowed values are true and false (the default is false). When the value is true, the effect is that if your scope authorization request is granted, the Google authorization server will roll this authorization together with all the previous authorizations granted to the requesting user from the requesting app. The URI you construct might end up looking this this (line breaks and space inserted for readability):

https://accounts.google.com/o/oauth2/auth?
  scope=https://www.googleapis.com/auth/drive.file&
  state=%2Fprofile&
  redirect_uri=https%3A%2F%2Fmyapp.example.com%2Fcallback&
  response_type=code&
  client_id=8127352506391.apps.googleusercontent.com&
  approval_prompt=force&
  include_granted_scopes=true

Let’s call the resulting authorization the “combined authorization”; the following apply:

  • You can use the access tokens you get to access the resources corresponding to any of the scopes that are rolled into the combined authorization.
  • When you use the refresh token for a combined authorization, the new access tokens represent the combined authorization and can be used for any of its scopes.
  • The combined authorization includes any previously granted authorizations even if they were requested from different clients. For example, if you requested the https://www.googleapis.com/auth/plus.login scope from a desktop app, and then issued the request in the example URI above for the same user from a mobile app, and it was granted, the combined authorization would include both scopes.
  • When you revoke a token which represents a combined authorization, all of the authorizations are revoked simultaneously; this means that if you retain a token for one of the previous authorizations, it will stop working.

Offline access

In some cases, your application may need to access a Google API when the user is not present. Examples of this include backup services and applications that make blogger posts exactly at 8am on Monday morning. This style of access is called offline, and web server applications may request offline access from a user. The normal and default style of access is called online.

If your application needs offline access to a Google API, then the request for an authorization code should include the access_type parameter, where the value of that parameter is offline. An example request for offline access is shown below, with line breaks and spaces for readability:

https://accounts.google.com/o/oauth2/auth?
 scope=email%20profile&
 state=%2Fprofile&
 redirect_uri=https%3A%2F%2Foauth2-login-demo.appspot.com%2Fcode&
 response_type=code&
 client_id=812741506391.apps.googleusercontent.com&
 access_type=offline

The first time a given user's browser is sent to this URL, they see a consent page. If they grant access, then the response includes an authorization code which may be redeemed for an access token and a refresh token.

An example of an authorization code exchange is shown below:

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code

If this is the first time the application has exchanged an authorization code for a user, then the response includes an access token and a refresh token, as shown below:

{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer",
  "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

Important: When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the approval_prompt parameter in the authorization code request, and set the value to force.

After your application receives the refresh token, it may obtain new access tokens at any time. See the section on refresh tokens for more information.

The next time your application requests an authorization code for that user, the user will not be asked to grant consent (assuming they previously granted access, and you are asking for the same scopes). As expected, the response includes an authorization code which may be redeemed. However, unlike the first time an authorization code is exchanged for a given user, a refresh token will not be returned from the authorization code exchange. The following is an example of such a response:

{
  "access_token":"1/fFAGRNJru1FQd77BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer",
}

Using a refresh token

As indicated in the previous section, a refresh token is obtained in offline scenarios during the first authorization code exchange. In these cases, your application may obtain a new access token by sending a refresh token to the Google OAuth 2.0 Authorization server.

To obtain a new access token this way, your application sends an HTTPS POST request to https://accounts.google.com/o/oauth2/token. The request must include the following parameters:

Field Description
refresh_token The refresh token returned from the authorization code exchange.
client_id The client ID obtained from the Developers Console.
client_secret The client secret obtained from the Developers Console.
grant_type As defined in the OAuth 2.0 specification, this field must contain a value of refresh_token.

Such a request will look similar to the following:

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
refresh_token=1/6BMfW9j53gdGImsiyUH5kU5RsR4zwI9lUVX-tqf8JXQ&
grant_type=refresh_token

As long as the user has not revoked the access granted to your application, the response includes a new access token. A response from such a request is shown below:

{
  "access_token":"1/fFBGRNJru1FQd44AzqT3Zg",
  "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

In some cases a user may wish to revoke access given to an application. A user can revoke access by visiting the following URL and explicitly revoking access: https://accounts.google.com/b/0/IssuedAuthSubTokens. 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.

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

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.

Client libraries

The following client libraries make implementing OAuth 2.0 simpler by integrating with popular frameworks:

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.