Oauth 2.0 in Google API

https://developers.google.com/accounts/docs/OAuth2

Google APIs use the OAuth 2.0 protocol for authentication and authorization. Google supports several OAuth 2.0 flows that cover common web server, JavaScript, device, installed application, and server to server scenarios.

OAuth 2.0 is a relatively simple protocol and a developer can integrate with Google’s OAuth 2.0 endpoints without too much effort. In a nutshell, you register your application with Google, redirect a browser to a URL, parse a token from the response, and send the token to the Google API you wish to access.

This article gives an overview of the OAuth 2.0 scenarios Google supports and provides links to more detailed content.

Given the security implications of getting the implementation correct, we strongly encourage developers to use OAuth 2.0 libraries when interacting with Google’s OAuth 2.0 endpoints (see Client libraries for more information). Over time, more features will be added to these libraries.

Contents

  1. Basic Steps
  2. Simple Example
  3. Scenarios
    1. Login
    2. Web Server Applications
    3. Client-side Applications
    4. Installed Applications
    5. Devices
    6. Service Accounts
  4. Client Libraries

Basic Steps

Applications follow the same basic pattern when accessing a Google API using OAuth 2.0. At a high level, using OAuth 2.0 to access a Google API consists of four steps:

1. Register Application

All applications that access a Google API must be registered through the APIs Console. The result of this registration process is a set of values that are known to both Google and your application (e.g. client_idclient_secret, JavaScript origins, redirect_uri, etc.). The set of values generated varies based on what type of application you are building. For example a JavaScript application does not require a secret, but a web server application does.

2. Obtain an Access Token from the Google Authorization Server

Before your application can access a Google API, it must obtain an access token that grants access to that API. A single access token may grant varying degrees of access to multiple APIs. The set of resources and operations permitted by an access token is controlled during the access token request via a variable parameter called ‘scope’. Several scopes may be included in a request.

There are several ways to make this request, and they vary based on the type of application you are building. For example, a JavaScript application may request an access token using a browser redirect to Google, while an application installed on a device that has no browser uses web service requests.

The request requires the user to login to Google. After logging in, the user will see the permissions requested by the application and is asked if they are willing to grant your application those permissions. This process is called “user consent”.

If the user grants permission to your application, your application will be sent an access token or an authorization code (which is used to obtain an access token). If the user does not grant permission to your application, the Google Authorization Server returns an error.

3. Send Access Token to an API

After an application has obtained an access token, it may send the access token in a request to a Google API. Access tokens are valid only for the set of operations and resources described in the token request. For example, if an access token is issued for the Google+ API, it will not grant access to the Google Contacts API. It may, however, be sent to the Google+ API multiple times for similar operations. Access tokens are sent to a Google API in the HTTP Authorization header, or as a query string parameter (if HTTP header operations are not available).

4. Refresh the Access Token (optional)

Access tokens have a limited lifetime and, in some cases, an application needs access to a Google API beyond the lifetime of a single access token. When this is the case, your application can obtain what is called a refresh token. A refresh token allows your application to obtain new access tokens.

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.

Simple Example

Below is a trivial example of how to use Google’s OAuth 2.0 endpoint to gain access to a Google API. It’s a Python web application running on App Engine. The flow of the example is fairly straightforward:

  1. When the application loads, it shows the you a “Login” link.
  2. When you click that link, you are asked to login to Google and asked to release basic account information to the application (user consent).
  3. If you grant consent, the application receives an access token.
  4. Once it has the access token, the application presents the access token to the Google API that provides basic account information (https://www.googleapis.com/oauth2/v1/userinfo)
  5. The application renders the basic account information in a simple table.

Try it out for yourself!

Scenarios

Login

User login is clearly an essential part of most Google API access, but Google’s authentication system can be used by your application as a stand-alone component. In other words, you can outsource user authentication and profile acquisition to Google.

The login sequence starts by redirecting the browser (popup, or full-page if needed) to a Google URL with a set of query string parameters. Google handles selecting the correct session (if the user has previously logged in with multiple identities), accepting and validating the user credentials and one-time-passwords (if the account requires it), obtaining consent to release basic profile information, as well as minting and returning an OAuth access token to your application.

The result of the user authentication sequence is an OAuth 2.0 access token, and you may then obtain user profile information (name, email address, verified email address, profile picture, etc.) by calling a the UserInfo Google API.

The information returned from UserInfo can be used during user registration and can dramatically improve registration success rates. There’s also the added benefit that your site doesn’t have to build, maintain, and secure a username / password store.

For more information, see the Login documentation.

Web Server Applications

The Google OAuth 2.0 Authorization Server supports web server applications (e.g. PHP, Java, Python, Ruby, ASP.NET, etc.). This sequence begins by redirecting a browser (popup, or full-page if needed) to a Google URL with a set of query parameters that indicate the type of Google API access the application requires. Like other scenarios, Google handles the user authentication, session selection and consent, but the result of the sequence is an authorization code. After receiving the authorization code, the application can exchange the code for an access token and a refresh token.

The application may access a Google API after it receives the access token.

For more information, see the Web Server documentation.

Client-side Applications

The Google OAuth 2.0 Authorization Server supports JavaScript applications (JavaScript running in a browser). Like the other scenarios, this one begins by redirecting a browser (popup, or full-page if needed) to a Google URL with a set of query string parameters that indicate the type of Google API access the application requires. Google handles the user authentication, session selection, and user consent. The result is an access token. The client should then validate the token. After validation, the client includes the access token in a Google API request.

For more information, see the Client-side documentation.

Installed Application

The Google OAuth 2.0 Authorization Server supports desktop and mobile applications (e.g. Android, Windows, Mac OS, iOS, Blackberry, etc.). These applications, in general, cannot keep secrets.

The sequence for installed applications is similar to the one shown in the Web Server section, but there are three exceptions:

  1. When registering the application, you specify that the application is an Installed application. This results in a different value for the redirect_uri parameter.
  2. The client_id and client_secret obtained during registration are embedded in the source code of your application. In this context, the client_secret is obviously not treated as a secret.
  3. The authorization code is returned to your application differently.

This sequence begins by redirecting a browser (either a browser embedded in the application or the system browser) to a Google URL with a set of query parameters that indicate the type of Google API access the application requires. Like other scenarios, Google handles the user authentication, session selection, and user consent. The result of the sequence is an authorization code. Your application can choose to have the authorization code returned in the title of the web page or to a http://localhost port. Once the application receives the authorization code, it can exchange the code for an access token and a refresh token.

After the application has received the access and refresh tokens, it may store the refresh token for future use, and use the access token to access a Google API. Once the access token expires, the application obtains a new one with the refresh token.

For more information, see the Installed Application documentation.

Devices

The Google OAuth 2.0 Authorization Server supports applications that run on devices with limited input capabilities (e.g. game consoles, video cameras, printers). In these cases, the user must have separate access to a computer or device with richer input capabilities. The user will first interact with application on the limited device, obtain an URL and a code from the device, then switch to a device or computer with richer input capabilities and launch a browser. Once in a browser, the user will navigate to the URL specified on the device, authenticate, and enter the code.

The sequence begins with the application making a request to a Google URL for a new code. The response contains several parameters, including the URL and code that should be shown to the user. The application should present these values to the user, and begin polling a Google URL at a specified interval. The response to a message in this polling sequence indicates whether or not the user has approved access. After the user approves access (via another computer or device), the response contains an access and refresh token.

After the application has received the access and refresh tokens, it may store the refresh token for future use, and use the access token to access a Google API. Once the access token expires, the application obtains a new one with the refresh token.

For more information, see the Device documentation.

Service Accounts

Several Google APIs act on behalf of an application and do not access user information. Examples of these APIs include the Prediction API and Google Cloud Storage. When an application accesses Google Cloud Storage, the application needs to prove its own identity before performing storage operations so there is no need to gain a users approval. There’s also an option for an application to request delegated access to a resource in enterprise scenarios. Google’s OAuth 2.0 Authorization Server supports these types of applications, and this section describes how an application can prove its identity before accessing a compatible Google API.

The mechanics of this interaction require applications to create and cryptographically sign JSON Web Tokens (JWTs). Developers are strongly encouraged to use a library to perform these tasks. Writing this code without the use of a library that abstracts token creation and signing is prone to errors that can have a severe impact on the security of your application. For a list of libraries that support this flow, see the OAuth 2.0 Service Accounts documentation

This sequence begins with the creation of a Service Account. You may create a Service Account in the Google APIs Console, or if you are using Google App Engine, one is created automatically for your Google App Engine application. During the creation of a Service Account in the Google APIis Console you will be prompted to download a private key. Be sure to save this private key in a secure location. After the Service Account has been created, you will also have access to the client ID associated with the private key. You will need both when coding your application.

After obtaining the client ID and private key from the Google APIs Console, create a JWT and sign it with the private key, and construct an access token request in the appropriate format. Your application then sends the token request to the Google OAuth 2.0 Authorization Server and an access token will be returned. The application can access the API only after receiving the access token. When the access token expires, the application repeats the process.

For more information, see the Service Account documentation.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s