OAuth 2.0 for Mobile & Desktop Apps

Note: If you are new to OAuth 2.0, we recommend that you read the OAuth 2.0 overview before getting started. The overview summarizes OAuth 2.0 flows that Google supports, which can help you to ensure that you've selected the right flow for your application.

This document explains how applications installed on devices like phones, tablets, and computers use Google's OAuth 2.0 endpoints to authorize access to Google APIs. 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.

Installed apps are distributed to individual devices, and it is assumed that these apps cannot keep secrets. They can access Google APIs while the user is present at the app or when the app is running in the background.

This authorization flow is similar to the one used for web server applications. The main difference is that installed apps must open the system browser and supply a local redirect URI to handle responses from Google's authorization server.

Alternatives

For mobile apps, you may prefer to use Google Sign-in for Android or iOS. The Google Sign-in client libraries handle authentication and user authorization, and they may be simpler to implement than the lower-level protocol described here.

For apps running on devices that do not support a system browser or that have limited input capabilities, such as TVs, game consoles, cameras, or printers, see OAuth 2.0 for TVs & Devices or Google Sign-in for devices.

Libraries and samples

We recommend the following libraries and samples to help you implement the OAuth 2.0 flow described in this document:

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:

  1. Open the Library page in the API Console.
  2. Select the project associated with your application. Create a project if you do not have one already.
  3. 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.

  1. Open the Credentials page in the API Console.
  2. Click Create credentials > OAuth client ID.
  3. Complete the form. The sections below describe the redirect methods that Google's authorization server supports. Choose the one that is recommended for your application and set the other fields in the form as appropriate.
    • Option 1: Custom URI scheme (Android, iOS, UWP)

      Recommended usage Android apps, iOS apps, Universal Windows Platform (UWP) apps
      Form values Set the application type to Android for Android apps and to iOS otherwise. Also set the package name or bundle ID – the field that is present depends on the application type – to the custom URI scheme that you will use in the redirect (e.g. com.example.app). Additionally, you can use the reverse DNS notion of the client ID as the custom URI scheme (e.g. com.googleusercontent.apps.123).

      For UWP apps, the scheme cannot be longer than 39 characters.

      Note: See the redirect_uri parameter definition for details about the format of the custom URI scheme value. In addition, the libraries and samples demonstrate some platform-specific implementations of custom URI scheme redirects.

    • Option 2: Loopback IP address (macOS, Linux, Windows desktop)

      To receive the authorization code using this URL, your application must be listening on the local web server. That is possible on many, but not all, platforms. However, if your platform supports it, this is the recommended mechanism for obtaining the authorization code.

      When your app receives the authorization response, for best usability it should respond by displaying an HTML page that instructs the user to close the browser and return to your app.

      Recommended usage macOS, Linux, and Windows desktop (but not Universal Windows Platform) apps
      Form values Set the application type to Other.

      Note: See the redirect_uri parameter definition for more information about the loopback IP address. It is also possible to use localhost in place of the loopback IP, but this may cause issues with client firewalls. Most, but not all, firewalls allow loopback communication.


    • Option 3: Manual copy/paste

      Important: The custom URI scheme and loopback IP address options now provide more reliable, secure, and user-friendly ways to obtain user authorization. This option may be discontinued in the future and should only be used if the choices above are not viable.

    • Option 4: Programmatic extraction

      Important: This method is identical to the manual copy/paste method described above except the confirmation page does not instruct the user to copy the authorization code. Instead, the page just asks the user to close the window.

      This option is deprecated for OAuth 2.0 to Google. It was designed for embedded browsers, or web-views. The custom URI scheme and loopback IP address options now provide more reliable, secure, and user-friendly ways to obtain user authorization.

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.

Note: Incremental authorization is not supported for installed apps or devices.

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: Generate a code verifier and challenge

Google supports the Proof Key for Code Exchange protocol to make the installed app flow more secure. A unique code verifier is created for every authorization request, and its transformed value, called "code_challenge", is sent to the authorization server to obtain the authorization code.

Create the code verifier

A code_verifier is a high-entropy cryptographic random string using the unreserved characters [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~", with a minimum length of 43 characters and a maximum length of 128 characters.

The code verifier should have enough entropy to make it impractical to guess the value.

Create the code challenge

Two methods of creating the code challenge are supported.

Code Challenge Generation Methods
plain The code challenge is the same value as the code verifier generated above.
code_challenge = code_verifier
S256 The code challenge is the Base64URL (with no padding) encoded SHA256 hash of the code verifier.
code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))

Step 2: Send a request to Google's OAuth 2.0 server

To obtain user authorization, send a request to Google's authorization server at https://accounts.google.com/o/oauth2/v2/auth. This endpoint handles active session lookup, authenticates the user, and obtains user consent. The endpoint is only accessible over SSL, and it refuses HTTP (non-SSL) connections.

The authorization server supports the following query string parameters for installed applications:

Parameters
client_id Required. The client ID for your application. You can find this value in the API Console.
redirect_uri Required. Determines how Google's authorization server sends a response to your app. There are several redirect options available to installed apps, and you will have set up your authorization credentials with a particular redirect method in mind.

The table below shows the appropriate redirect_uri parameter value for each method:
redirect_uri values
Custom URI scheme com.example.app:redirect_uri_path or
com.googleusercontent.apps.123:redirect_uri_path
  • com.example.app is the reverse DNS notation of a domain under your control. The custom scheme must contain a period to be valid.
  • com.googleusercontent.apps.123 is the reverse DNS notation of the client ID.
  • redirect_uri_path is an optional path component, such as /oauth2redirect. Note that the path should begin with a single slash, which is different from regular HTTP URLs.
Loopback IP address http://127.0.0.1:port or http://[::1]:port

Query your platform for the relevant loopback IP address and start an HTTP listener on a random available port. Substitute port with the actual port number your app is listening on.
Manual copy/paste urn:ietf:wg:oauth:2.0:oob
Programmatic extraction urn:ietf:wg:oauth:2.0:oob:auto
response_type Required. Determines whether the Google OAuth 2.0 endpoint returns an authorization code. Set the parameter value to code for installed applications.
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.
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.
code_challenge_method Recommended. Specifies what method was used to encode a code_verifier that will be used during authorization code exchange. This parameter must be used with the code_challenge parameter. The value of the code_challenge_method defaults to "plain" if not present in the request that includes a code_challenge. The only supported values for this parameter are "S256" or "plain".
code_challenge Recommended. Specifies an encoded code_verifier that will be used as a server-side challenge during authorization code exchange. This parameter must be used with the code_challenge parameter described above. See create code challenge section above for more information.
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.

Note: Due to the fact that the client cannot keep the client_secret confidential, you cannot do incremental authorization with installed apps.

Sample authorization URLs

The tabs below show sample authorization URLs for the different redirect URI options. The URLs are identical except for the value of the redirect_uri parameter. The URLs also contain the required response_type and client_id parameters as well as the optional state parameter. Each URL contains line breaks and spaces for readability.

Custom URI scheme

https://accounts.google.com/o/oauth2/v2/auth?
 scope=email%20profile&
 response_type=code&
 state=security_token%3D138r5719ru3e1%26url%3Dhttps://oauth2.example.com/token&
 redirect_uri=com.example.app:/oauth2redirect&
 client_id=client_id

Loopback IP address

https://accounts.google.com/o/oauth2/v2/auth?
 scope=email%20profile&
 response_type=code&
 state=security_token%3D138r5719ru3e1%26url%3Dhttps://oauth2.example.com/token&
 redirect_uri=http://127.0.0.1:9004&
 client_id=client_id

Copy/Paste

Important: This redirect URI option uses practices that may be less secure or user-friendly than other options.

https://accounts.google.com/o/oauth2/v2/auth?
 scope=email%20profile&
 response_type=code&
 state=security_token%3D138r5719ru3e1%26url%3Dhttps://oauth2.example.com/token&
 redirect_uri=urn:ietf:wg:oauth:2.0:oob&
 client_id=client_id

Programmatic extraction

Important: This redirect URI option, which is designed for embedded browsers, is deprecated. Like the copy/paste option, it uses practices that may be less secure or user-friendly than other options.

https://accounts.google.com/o/oauth2/v2/auth?
 scope=email%20profile&
 response_type=code&
 state=security_token%3D138r5719ru3e1%26url%3Dhttps://oauth2.example.com/token&
 redirect_uri=urn:ietf:wg:oauth:2.0:oob:auto&
 client_id=client_id

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

The manner in which your application receives the authorization response depends on the redirect URI scheme that it uses. Regardless of the scheme, the response will either contain an authorization code (code) or an error (error). For example, error=access_denied indicates that the user declined the request.

If the user grants access to your application, you can exchange the authorization code for an access token and a refresh token as described in the next step.

Step 5: Exchange authorization code for refresh and access tokens

To exchange an authorization code for an access token, call the https://www.googleapis.com/oauth2/v4/token endpoint and set the following parameters:

Fields
code The authorization code returned from the initial request.
client_id The client ID obtained from the API Console.
client_secret The client secret obtained from the API Console. This value is not needed for clients registered as Android, iOS, or Chrome applications.
redirect_uri One of the redirect URIs listed for your project in the API Console.
grant_type As defined in the OAuth 2.0 specification, this field must contain a value of authorization_code.
code_verifier The code verifier you created in Step 1.

The following snippet shows a sample request:

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=https://oauth2.example.com/code&
grant_type=authorization_code

Google responds to this request by returning a JSON object that contains a short-lived access token and a refresh token.

The response contains the following fields:

Fields
access_token The token that your application sends to authorize a Google API request.
id_token Note: This property is only returned if your request included an identity scope, such as openid, profile, or email. The value is a JSON Web Token (JWT) that contains digitally signed identity information about the user.
refresh_token A token that you can use to obtain a new access token. Refresh tokens are valid until the user revokes access. Note that refresh tokens are always returned for installed applications.
expires_in The remaining lifetime of the access token in seconds.
token_type The type of token returned. At this time, this field's value is always set to Bearer.

Important: Your application should store both tokens in a secure, long-lived location that is accessible between different invocations of your application. The refresh token enables your application to obtain a new access token if the one that you have expires. As such, if your application loses the refresh token, the user will need to repeat the OAuth 2.0 consent flow so that your application can obtain a new refresh token.

The following snippet shows a sample response:

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

Calling Google APIs

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:

GET https://www.googleapis.com/drive/v2/files?access_token=<access_token>

curl examples

You can test these commands with the curl command-line application. Here's an example that uses the HTTP header option (preferred):

curl -H "Authorization: Bearer <access_token>" https://www.googleapis.com/drive/v2/files

Or, alternatively, the query string parameter option:

curl https://www.googleapis.com/drive/v2/files?access_token=<access_token>

Refreshing an access token

Access tokens periodically expire. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.

To refresh an access token, your application sends an HTTPS POST request to Google's authorization server (https://www.googleapis.com/oauth2/v4/token) that includes the following parameters:

Fields
refresh_token The refresh token returned from the authorization code exchange.
client_id The client ID obtained from the API Console.
client_secret The client secret obtained from the API Console. (The client_secret is not applicable to requests from clients registered as Android, iOS, or Chrome applications.)
grant_type As defined in the OAuth 2.0 specification, this field must contain a value of refresh_token.

The following snippet shows a sample request:

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

client_id=<your_client_id>&
client_secret=<your_client_secret>&
refresh_token=<refresh_token>&
grant_type=refresh_token

As long as the user has not revoked the access granted to the application, the token server returns a JSON object that contains a new access token. The following snippet shows a sample response:

{
  "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

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.

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

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.

Further Reading

The Internet-Draft Best Current Practice: OAuth 2.0 for Native Apps establishes many of the best practices documented here.