Google Accounts Authentication and Authorization

Using OAuth 2.0 for Installed Applications

The Google OAuth 2.0 endpoint supports applications that are installed on a device such as a computer, phone, or tablet. Installed apps are distributed to individual machines, and it is assumed that these apps cannot keep secrets. These apps might access a Google API while the user is present at the app, or when the app is running in the background.

If you are developing for Android or iOS, use Google+ Sign-In.

This document is for you if:

  • You are writing an installed app for a platform other than Android or iOS, and
  • Your installed app will run on devices that have a system browser and rich input capabilities, for example devices with full keyboards.

If you are writing an app for Android or iOS, use Google+ Sign-In to authenticate your users. The Google+ Sign-In button manages the OAuth 2.0 flow both for authentication and for obtaining authorization to Google APIs. Google+ Sign-In works for all users with a Google account, whether or not they have upgraded to Google+. To add the Google+ Sign-In button, follow the steps for Android or iOS.

If your app will run on devices that do not have access to a system browser, or devices with limited input capabilities (for example if your app will run on game consoles, video cameras, or printers), then see Using OAuth 2.0 for Devices.

Contents

  1. Overview
  2. Forming the URL for an authentication request
    1. Example URL
    2. Choosing a redirect URI
  3. Handling the response and making a token request
  4. Calling a Google API
  5. Incremental authorization
  6. Using a refresh token
  7. Client libraries

Overview

In this flow, the installed application must either have access to the system browser, or it must have a browser embedded as a web view. The OAuth 2.0 flow for installed applications is as follows:

  • Your application redirects a browser to a Google URL, and the URL query parameters indicate the type of Google API access that the application requires.
  • As in other scenarios, Google handles user authentication and consent, and the result of the sequence is an authorization code. The authorization code is returned in the title bar of the browser or as a query string parameter, depending on the parameters your application sends in the request.
  • Your application exchanges the authorization code for an access token and a refresh token. During this exchange, the application presents its client ID and client secret (obtained from the Developers Console).
  • Your application uses the access token to make calls to a Google API and stores the refresh token for future use.
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.

This flow is similar to the one shown in the Using OAuth 2.0 for Web Server Applications, but with three differences:

  • When creating a client ID, you specify that your application is an Installed application. This results in a different value for the redirect_uri parameter.
  • The client ID and client secret obtained from the Developers Console are embedded in the source code of your application. In this context, the client secret is obviously not treated as a secret.
  • The authorization code can be returned to your application in the title bar of the browser or to an http://localhost port in the query string.

Forming the URL for an authentication request

The URL to use when authenticating a user is https://accounts.google.com/o/oauth2/auth. This endpoint is accessible over SSL, and HTTP (non-SSL) 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. When your application sends a request to this endpoint, the response includes an access token, a refresh token, and an authorization code.

The query string parameters supported by the Google Authorization Server for installed applications are:

Parameter Values Description
response_type code For installed applications, use a value of code, indicating that the Google OAuth 2.0 endpoint should return an authorization 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 obtained from the Google Developers Console. Determines where the response is sent. The value of this parameter must exactly match one of the values that appear in the Credentials page in the Google Developers Console (including the http or https scheme, case, and trailing slash). You may choose between urn:ietf:wg:oauth:2.0:oob or an http://localhost port. For more details, see Choosing a redirect URI.
scope Space-delimited set of scope strings. 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 may be 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 information 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.
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.

Example URL

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

https://accounts.google.com/o/oauth2/auth?
  scope=email%20profile&
  redirect_uri=urn:ietf:wg:oauth:2.0:oob&
  response_type=code&
  client_id=812741506391-h38jh0j4fv0ce1krdkiq0hfvt6n5amrf.apps.googleusercontent.com

If the user logs in and grants access via a URL similar to the one shown above, the result is a dialog similar to the following:

Another example URL is shown below, with line breaks and spaces for readability:

https://accounts.google.com/o/oauth2/auth?
  scope=email%20profile&
  redirect_uri=http://localhost:9004&
  response_type=code&
  client_id=812741506391-h38jh0j4fv0ce1krdkiq0hfvt6n5amrf.apps.googleusercontent.com

The difference between these two URLs is the redirect_uri parameter. The first one results in an authorization code in the title of the page, and the second one results in the authorization code sent to a http://localhost address as part of the query string.

Choosing a redirect URI

When you create a client ID in the Google Developers Console, two redirect_uris are created for you: urn:ietf:wg:oauth:2.0:oob and http://localhost. The value your application uses determines how the authorization code is returned to your application.

http://localhost

This value signals to the Google Authorization Server that the authorization code should be returned as a query string parameter to the web server on the client. You may specify a port number without changing the Google Developers Console configuration. To receive the authorization code using this URL, your application must be listening on the local web server. This is possible on many, but not all, platforms. If your platform supports it, this is the recommended mechanism for obtaining the authorization code.

Note: In some cases, although it is possible to listen, other software (such as a Windows firewall) prevents delivery of the message without significant client configuration.

urn:ietf:wg:oauth:2.0:oob

This value signals to the Google Authorization Server that the authorization code should be returned in the title bar of the browser. This is useful when the client (such as a Windows application) cannot listen on an HTTP port without significant client configuration.

When you use this value, your application can then detect that the page has loaded, and can read the title of the HTML page to obtain the authorization code. It is then up to your application to close the browser window if you want to ensure that the user never sees the page that contains the authorization code. The mechanism for doing this varies from platform to platform.

Handling the response and making a token request

The response to the initial authentication request includes an authorization code (code), which your application can exchange for an access token and a refresh token. To make this token request, send an HTTP POST request to the /o/oauth2/token endpoint, and include the following parameters:

Field Description
code The authorization code returned from the initial request.
client_id The client ID you obtained from the Google Developers Console.
client_secret The client secret you obtained from the Developers Console.
redirect_uri The redirect URI you obtained from 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/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&
client_id=8819981768.apps.googleusercontent.com&
client_secret=your_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, included by default for installed applications. Refresh tokens are valid until the user revokes access.
expires_in The remaining lifetime of the access token.
token_type Identifies the type of token returned. Currently, this field always has the value 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.

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

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

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.

Using a refresh token

To obtain a new access token, send 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 you obtained from the Google Developers Console.
client_secret The client secret you 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 looks 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=your_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.

Client libraries

The following client libraries make implementing OAuth 2.0 simpler by integrating with popular programming languages and 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.