This document explains how applications installed on devices like phones, tablets, and computers use Google's OAuth 2.0 endpoints to authorize access to the YouTube Analytics API or the YouTube Reporting API.
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 to retrieve a channel's YouTube Analytics data.
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 Sign-In on TVs and Limited Input Devices.
Libraries and samples
We recommend the following libraries and samples to help you implement the OAuth 2.0 flow described in this document:
- AppAuth for Android library
- AppAuth for iOS library
- OAuth for Apps: Windows Samples
Prerequisites
Enable APIs for your project
Any application that calls Google APIs needs to enable those APIs in the API Console.
To enable an API for your project:
- Open the API Library in the Google API Console.
- If prompted, select a project, or create a new one.
- Use the Library page to find and enable the YouTube Analytics API and the YouTube Reporting API. Many applications that retrieve YouTube Analytics data also interface with the YouTube Data API. Find any other APIs that your application will use and enable those, too.
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.
- Go to the Credentials page.
- Click Create credentials > OAuth client ID.
- The following sections describe the client types that Google's authorization server supports. Choose the client type that is recommended for your application, name your OAuth client, and set the other fields in the form as appropriate.
Android
- Select the Android application type.
- Enter a name for the OAuth client. This name is displayed on your project's Credentials page to identify the client.
- Enter the package name of your Android app. This value is defined in the
package
attribute of the<manifest>
element in your app manifest file. - Enter the SHA-1 signing certificate fingerprint of the app distribution.
- If your app uses app signing by Google Play, copy the SHA-1 fingerprint from the app signing page of the Play Console.
- If you manage your own keystore and signing keys, use the keytool utility
included with Java to print certificate information in a human-readable format. Copy the
SHA1
value in theCertificate fingerprints
section of the keytool output. See Authenticating Your Client in the Google APIs for Android documentation for more information.
- (Optional) Verify ownership of your Android application.
- Click Create.
iOS
- Select the iOS application type.
- Enter a name for the OAuth client. This name is displayed on your project's Credentials page to identify the client.
- Enter the bundle identifier for your app. The bundle ID is the value of the
CFBundleIdentifier
key in your app's information property list resource file (info.plist). The value
is most commonly displayed in the General pane or the Signing & Capabilities pane of the
Xcode project editor. The bundle ID is also displayed in the General Information section of
the App Information page for the app on
Apple's App Store Connect site.
Confirm that you are using the correct bundle ID for your app, as you won't be able to change it if you are using the App Check feature.
- (Optional)
Enter your app's App Store ID if the app is published in Apple's App Store. The Store ID is a numeric string included in every Apple App Store URL.
- Open the Apple App Store app on your iOS or iPadOS device.
- Search for your app.
- Select the Share button (square and arrow up symbol).
- Select Copy Link.
- Paste the link into a text editor. The App Store ID is the final part of the URL.
Example:
https://apps.apple.com/app/google/id284815942
- (Optional)
Enter your Team ID. See Locate your Team ID in the Apple Developer Account documentation for more information.
Note: The Team ID field is required if you are enabling App Check for your client. - (Optional)
Enable App Check for your iOS app. When you enable App Check, Apple's App Attest service is used to verify that OAuth 2.0 requests originating from your OAuth client are genuine and come from your app. This helps to reduce the risk of app impersonation. Learn more about enabling App Check for your iOS app.
- Click Create.
UWP
- Select the Universal Windows Platform application type.
- Enter a name for the OAuth client. This name is displayed on your project's Credentials page to identify the client.
- Enter your app's 12-character Microsoft Store ID. You can find this value in Microsoft Partner Center on the App identity page in the App management section.
- Click Create.
For UWP apps, the custom URI scheme cannot be longer than 39 characters.
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 YouTube Analytics API uses the following scopes:
Scopes | |
---|---|
https://www.googleapis.com/auth/youtube | Manage your YouTube account |
https://www.googleapis.com/auth/youtube.readonly | View your YouTube account |
https://www.googleapis.com/auth/youtubepartner | View and manage your assets and associated content on YouTube |
https://www.googleapis.com/auth/yt-analytics-monetary.readonly | View monetary and non-monetary YouTube Analytics reports for your YouTube content |
https://www.googleapis.com/auth/yt-analytics.readonly | View YouTube Analytics reports for your YouTube content |
The YouTube Reporting API uses the following scopes:
Scopes | |
---|---|
https://www.googleapis.com/auth/yt-analytics-monetary.readonly | View monetary and non-monetary YouTube Analytics reports for your YouTube content |
https://www.googleapis.com/auth/yt-analytics.readonly | View YouTube Analytics reports for your YouTube content |
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: Generate a code verifier and challenge
Google supports the Proof Key for Code Exchange (PKCE) 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 | |
---|---|
S256 (recommended) | The code challenge is the Base64URL (with no padding) encoded SHA256 hash of the code
verifier.
|
plain | The code challenge is the same value as the code verifier generated above.
|
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 Credentials page. |
||||||||||||||||||
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 value must exactly match one of the authorized redirect URIs for the OAuth 2.0
client, which you configured in your client's
API Console
Credentials page. If this value doesn't match an
authorized URI, you will get a The table below shows the appropriate
|
||||||||||||||||||
response_type |
Required
Determines whether the Google OAuth 2.0 endpoint returns an authorization code. Set the parameter value to |
||||||||||||||||||
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 YouTube Analytics API uses the following scopes:
The YouTube Reporting API uses the following scopes:
The OAuth 2.0 API Scopes document provides a full list of scopes that you might use to access Google APIs. |
||||||||||||||||||
code_challenge |
Recommended
Specifies an encoded |
||||||||||||||||||
code_challenge_method |
Recommended
Specifies what method was used to encode a |
||||||||||||||||||
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 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 |
||||||||||||||||||
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 |
Sample authorization URLs
The tabs below show sample authorization URLs for the different redirect URI options.
Each URL requests access to a scope that permits access to retrieve the user's YouTube Analytics reports.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=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyt-analytics.readonly& response_type=code& state=security_token%3D138r5719ru3e1%26url%3Dhttps%3A%2F%2Foauth2.example.com%2Ftoken& redirect_uri=com.example.app%3A/oauth2redirect& client_id=client_id
Loopback IP address
https://accounts.google.com/o/oauth2/v2/auth? scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyt-analytics.readonly& response_type=code& state=security_token%3D138r5719ru3e1%26url%3Dhttps%3A%2F%2Foauth2.example.com%2Ftoken& redirect_uri=http%3A//127.0.0.1%3A9004& 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 and a summary of the scopes of access to be granted. The user can then consent to grant access to one or more scopes requested by your application or refuse the request.
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 any access was granted. That response is explained in the following step.
Errors
Requests to Google's OAuth 2.0 authorization endpoint may display user-facing error messages instead of the expected authentication and authorization flows. Common error codes and suggested resolutions are listed below.
admin_policy_enforced
The Google Account is unable to authorize one or more scopes requested due to the policies of their Google Workspace administrator. See the Google Workspace Admin help article Control which third-party & internal apps access Google Workspace data for more information about how an administrator may restrict access to all scopes or sensitive and restricted scopes until access is explicitly granted to your OAuth client ID.
disallowed_useragent
The authorization endpoint is displayed inside an embedded user-agent disallowed by Google's OAuth 2.0 Policies.
Android
Android developers may encounter this error message when opening authorization requests in
android.webkit.WebView
.
Developers should instead use Android libraries such as
Google Sign-In for Android or OpenID Foundation's
AppAuth for Android.
Web developers may encounter this error when an Android app opens a general web link in an embedded user-agent and a user navigates to Google's OAuth 2.0 authorization endpoint from your site. Developers should allow general links to open in the default link handler of the operating system, which includes both Android App Links handlers or the default browser app. The Android Custom Tabs library is also a supported option.
iOS
iOS and macOS developers may encounter this error when opening authorization requests in
WKWebView
.
Developers should instead use iOS libraries such as
Google Sign-In for iOS or OpenID Foundation's
AppAuth for iOS.
Web developers may encounter this error when an iOS or macOS app opens a general web link in
an embedded user-agent and a user navigates to Google's OAuth 2.0 authorization endpoint from
your site. Developers should allow general links to open in the default link handler of the
operating system, which includes both
Universal Links
handlers or the default browser app. The
SFSafariViewController
library is also a supported option.
org_internal
The OAuth client ID in the request is part of a project limiting access to Google Accounts in a specific Google Cloud Organization. For more information about this configuration option see the User type section in the Setting up your OAuth consent screen help article.
invalid_grant
If you are using a
code verifier and
challenge, the code_callenge
parameter is invalid or missing. Ensure that the
code_challenge
parameter is set correctly.
When refreshing an access token, the token may have expired or has beeninvalidated. Authenticate the user again and ask for user consent to obtain new tokens. If you are continuing to see this error, ensure that your application has been configured correctly and that you are using the correct tokens and parameters in your request. Otherwise, the user account may have been deleted or disabled.
redirect_uri_mismatch
The redirect_uri
passed in the authorization request does not match an authorized
redirect URI for the OAuth client ID. Review authorized redirect URIs in the
Google API Console Credentials page.
The passed redirect_uri
may be invalid for the client type.
The redirect_uri
parameter may refer to the OAuth out-of-band (OOB) flow that has
been deprecated and is no longer supported. Refer to the
migration guide to update your
integration.
invalid_request
There was something wrong with the request you made. This could be due to a number of reasons:
- The request was not properly formatted
- The request was missing required parameters
- The request uses an authorization method that Google doesn't support. Verify your OAuth integration uses a recommended integration method
- A custom scheme is used for the redirect uri : If you see the error message Custom URI scheme is not supported on Chrome apps or Custom URI scheme is not enabled for your Android client, it means you are using a custom URI scheme which isn't supported on Chrome apps and is disabled by default on Android. Learn more about custom URI scheme alternatives
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://oauth2.googleapis.com/token
endpoint and set the following parameters:
Fields | |
---|---|
client_id |
The client ID obtained from the API Console Credentials page. |
client_secret |
The client secret obtained from the API Console Credentials page. |
code |
The authorization code returned from the initial request. |
code_verifier |
The code verifier you created in Step 1. |
grant_type |
As defined in the OAuth 2.0
specification, this field's value must be set to authorization_code . |
redirect_uri |
One of the redirect URIs listed for your project in the
API Console
Credentials page for the given
client_id . |
The following snippet shows a sample request:
POST /token HTTP/1.1 Host: oauth2.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=http://127.0.0.1:9004& 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. |
expires_in |
The remaining lifetime of the access token in seconds. |
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. |
scope |
The scopes of access granted by the access_token expressed as a list of
space-delimited, case-sensitive strings. |
token_type |
The type of token returned. At this time, this field's value is always set to
Bearer . |
The following snippet shows a sample response:
{ "access_token": "1/fFAGRNJru1FTz70BzhT3Zg", "expires_in": 3920, "token_type": "Bearer", "scope": "https://www.googleapis.com/auth/yt-analytics.readonly https://www.googleapis.com/auth/calendar.readonly", "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI" }
Step 6: Check which scopes users granted
When requesting multiple scopes at once, users may not grant all scopes your app requests. Your app should always check which scopes were granted by the user and handle any denial of scopes by disabling relevant features. Review How to handle granular permissions for more information.
To check whether the user has granted your application access to a particular scope,
exam the scope
field in the access token response. The scopes of access granted by
the access_token expressed as a list of space-delimited, case-sensitive strings.
For example, the following sample access token response indicates that the user has granted your application access to the read-only Drive activity and Calendar events permissions:
{ "access_token": "1/fFAGRNJru1FTz70BzhT3Zg", "expires_in": 3920, "token_type": "Bearer", "scope": "https://www.googleapis.com/auth/yt-analytics.readonly https://www.googleapis.com/auth/calendar.readonly", "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 if the scope(s) of access required by the API have been granted. To do this, include
the access token in a request to the API by including either an access_token
query
parameter or an Authorization
HTTP header Bearer
value. 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 YouTube Analytics API).
Note that the YouTube Analytics API does not support the service account flow. The YouTube Reporting API supports service accounts only for YouTube content owners that own and manage multiple YouTube channels, such as record labels and movie studios.
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
reports.query
endpoint (the YouTube Analytics API) using the Authorization: Bearer
HTTP
header might look like the following. Note that you need to specify your own access token:
GET /youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date=2016-05-01&end-date=2016-06-30&metrics=views HTTP/1.1 Host: www.googleapis.com Authorization: Bearer access_token
Here is a call to the same API for the authenticated user using the access_token
query string parameter:
GET https://www.googleapis.com/youtube/analytics/v1/reports?access_token=access_token&ids=channel%3D%3DMINE&start-date=2016-05-01&end-date=2016-06-30&metrics=views
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/youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date=2016-05-01&end-date=2016-06-30&metrics=views
Or, alternatively, the query string parameter option:
curl https://www.googleapis.com/youtube/analytics/v1/reports?access_token=access_token&ids=channel%3D%3DMINE&start-date=2016-05-01&end-date=2016-06-30&metrics=views
Refreshing an access token
Access tokens periodically expire and become invalid credentials for a related API request. 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://oauth2.googleapis.com/token
) that
includes the following parameters:
Fields | |
---|---|
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's value must be set to refresh_token . |
refresh_token |
The refresh token returned from the authorization code exchange. |
The following snippet shows a sample request:
POST /token HTTP/1.1 Host: oauth2.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, "scope": "https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/calendar.readonly", "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. See the Remove site or app access section of the Third-party sites & apps with access to your account support document for more information.
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, removes an application, or the API resources required by an app have significantly changed. In other words, part of the removal process can include an API request to ensure the permissions previously granted to the application are removed.
To programmatically revoke a token, your application makes a request to
https://oauth2.googleapis.com/revoke
and includes the token as a parameter:
curl -d -X -POST --header "Content-type:application/x-www-form-urlencoded" \ https://oauth2.googleapis.com/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 HTTP status code of the response is
200
. For error conditions, an HTTP status code 400
is returned along
with an error code.
App redirect methods
Custom URI scheme (Android, iOS, UWP)
Custom URI schemes are a form of deeplinking that use a custom-defined scheme to open your app.
Alternative to using custom URI schemes on Android
Use the Google Sign-In for Android SDK which delivers the OAuth 2.0 response directly to your app, eliminating the need for a redirect URI.
How to migrate to the Google Sign-In for Android SDK
If you use a custom scheme for your OAuth integration on Android, you would need to complete the following actions to fully migrate to using the recommended Google Sign-In for Android SDK:
- Update your code to use the Google Sign-In SDK.
- Disable support for custom scheme in the Google API Console.
Follow the below steps to migrate to the Google Sign-In Android SDK:
-
Update your code to use the Google Sign-In Android SDK:
-
Examine your code to identify where you are
sending a request to Google's OAuth 2.0 server; if using a custom scheme, your request would look like the below:
https://accounts.google.com/o/oauth2/v2/auth? scope=<SCOPES>& response_type=code& &state=<STATE>& redirect_uri=com.example.app:/oauth2redirect& client_id=<CLIENT_ID>
com.example.app:/oauth2redirect
is the custom scheme redirect URI in the above example. See theredirect_uri
parameter definition for more details about the format of the custom URI scheme value. -
Make note of the
scope
andclient_id
request parameters which you would need to configure the Google Sign-In SDK. -
Follow the
Start Integrating Google Sign-In into Your Android App
instructions to set up the SDK. You can skip the
Get your backend server's OAuth 2.0 client ID step as you would re-use
the
client_id
you retrieved from the previous step. -
Follow the
Enabling Server-Side API access
instructions. This includes the following steps:
-
Use the
getServerAuthCode
method to retrieve an auth code for the scopes you are requesting permission for. - Send the auth code to your app's backend to exchange it for an access & refresh token.
- Use the retrieved access token to make calls to Google APIs on behalf of the user.
-
Use the
-
Examine your code to identify where you are
sending a request to Google's OAuth 2.0 server; if using a custom scheme, your request would look like the below:
-
Disable support for custom scheme in the Google API Console:
- Go to your OAuth 2.0 credentials list and select your Android client.
- Navigate to the Advanced Settings section, uncheck the Enable Custom URI Scheme checkbox, and click Save to disable custom URI scheme support.
Enable custom URI scheme
If the recommended alternative does not work for you, you can enable custom URI schemes for your Android client by following the below instructions:- Go to your OAuth 2.0 credentials list and select your Android client.
- Navigate to the Advanced Settings section, check the Enable Custom URI Scheme checkbox, and click Save to enable custom URI scheme support.
Alternative to using custom URI schemes on Chrome apps
Use the Chrome Identity API which delivers the OAuth 2.0 response directly to your app, eliminating the need for a redirect URI.
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 Desktop app. |
Manual copy/paste (Deprecated)
Protect your apps
Verify app ownership (Android, Chrome)
You can verify ownership of your application to reduce the risk of app impersonation.
Android
To complete the verification process, you can use your Google Play Developer Account if you have one and your app is registered on the Google Play Console. The following requirements must be met for a successful verification:
- You must have a registered application in the Google Play Console with the same package name and SHA-1 signing certificate fingerprint as the Android OAuth client you are completing the verification for.
- You must have Admin permission for the app in the Google Play Console. Learn more about access management in the Google Play Console.
In the Verify App Ownership section of the Android client, click the Verify Ownership button to complete the verification process.
If the verification is successful, a notification will be displayed to confirm the success of the verification process. Otherwise, an error prompt will be shown.
To fix a failed verification, try the following:
- Make sure the app you are verifying is a registered app in the Google Play Console.
- Make sure you have Admin permission for the app in the Google Play Console.
Chrome
To complete the verification process, you would use your Chrome Web Store Developer account. The following requirements must be met for a successful verification:
- You must have a registered item in the Chrome Web Store Developer Dashboard with the same item ID as the Chrome Extension OAuth client you are completing the verification for.
- You must be a publisher for the Chrome Web Store item. Learn more about access management in the Chrome Web Store Developer Dashboard.
In the Verify App Ownership section of the Chrome Extension client, click the Verify Ownership button to complete the verification process.
Note: Wait a few minutes before completing the verification process after granting access to your account.
If the verification is successful, a notification will be displayed to confirm the success of the verification process. Otherwise, an error prompt will be shown.
To fix a failed verification, try the following:
- Make sure there is a registered item in the Chrome Web Store Developer Dashboard with the same item ID as the Chrome Extension OAuth client you are completing the verification for.
- Make sure you are a publisher for the app, that is, you must either be the individual publisher of the app or a member of the group publisher of the app. Learn more about access management in the Chrome Web Store Developer Dashboard.
- If you just updated your group publisher list, verify that the group publisher membership list is synced in the Chrome Web Store Developer Dashboard. Learn more about syncing your publisher membership list.
App Check (iOS only)
The App Check feature helps safeguard your iOS applications from unauthorized usage by using Apple's App Attest service to verify that requests made to Google OAuth 2.0 endpoints originate from your authentic applications. This helps to reduce the risk of app impersonation.
Enable App Check for your iOS Client
The following requirements must be met to successfully enable App Check for your iOS client:- You must specify a team ID for your iOS client.
- You must not use a wildcard in your bundle ID since it can resolve to more than one app. This means that the bundle ID must not include the asterisk (*) symbol.
After enabling App Check, you will start seeing metrics related to OAuth requests from your client in the edit view of the OAuth client. Requests from unverified sources won't be blocked until you enforce App Check. The information in the metrics monitoring page can help you determine when to start enforcement.
You might see errors related to the App Check feature when enabling App Check for your iOS app. To fix these errors, try the following:
- Verify that the bundle ID and team ID you specified are valid.
- Verify that you are not using a wildcard for the bundle ID.
Enforce App Check for your iOS Client
Enabling App Check for your app does not automatically block unrecognized requests. To enforce this protection, go to the edit view of your iOS client. There, you will see App Check metrics to the right of the page under the Google Identity for iOS section. The metrics include the following information:- Number of verified requests - requests that have a valid App Check token. After you enable App Check enforcement, only requests in this category will succeed.
- Number of unverified requests: likely outdated client requests - requests missing an App Check token; these request may be from an older version of your app that doesn't include an App Check implementation.
- Number of unverified requests: unknown origin requests - requests missing an App Check token that don't look like they are coming from your app.
- Number of unverified requests: invalid requests - requests with an invalid App Check token, which may be from an inauthentic client attempting to impersonate your app, or from emulated environments.
To enforce App Check, click the ENFORCE button and confirm your choice. Once enforcement is active, all unverified requests from your client will be rejected.
Note: after you enable enforcement, it can take up to 15 minutes for the changes to take effect.
Unenforce App Check for your iOS Client
Unenforcing App Check for your app will stop enforcement and will allow all requests from your client to Google OAuth 2.0 endpoints, including unverified requests.
To unenforce App Check for your iOS client, navigate to the edit view of the iOS client and click the UNENFORCE button and confirm your choice.
Note: after unenforcing App Check, it can take up to 15 minutes for the changes to take effect.
Disable App Check for your iOS Client
Disabling App Check for your app will stop all App Check monitoring and enforcement. Consider unenforcing App Check instead so you can continue monitoring metrics for your client.
To disable App Check for your iOS client, navigate to the edit view of the iOS client and turn off the Protect your OAuth client from abuse with Firebase App Check toggle button.
Note: after disabling App Check, it can take up to 15 minutes for the changes to take effect.
Further Reading
The IETF Best Current Practice OAuth 2.0 for Native Apps establishes many of the best practices documented here.
Implementing Cross-Account Protection
An additional step you should take to protect your users' accounts is implementing Cross-Account Protection by utilizing Google's Cross-Account Protection Service. This service lets you subscribe to security event notifications which provide information to your application about major changes to the user account. You can then use the information to take action depending on how you decide to respond to events.
Some examples of the event types sent to your app by Google's Cross-Account Protection Service are:
-
https://schemas.openid.net/secevent/risc/event-type/sessions-revoked
-
https://schemas.openid.net/secevent/oauth/event-type/token-revoked
-
https://schemas.openid.net/secevent/risc/event-type/account-disabled
See the Protect user accounts with Cross-Account Protection page for more information on how to implement Cross Account Protection and for the full list of available events.