Hide

Authentication using the Google APIs Client Library for JavaScript

Contents

  1. Overview
  2. Getting access keys for your application
  3. Simple access using the API key
  4. Authorized access
    1. OAuth 2.0 basics
    2. About scope
    3. OAuth 2.0 authorization flow
  5. Auth example
    1. Specifying your client ID and scopes
    2. Making the API request
  6. Making a request with CORS
  7. The standalone auth client

Overview

To access a user's private data, your application must work with Google's policies for authentication and authorization.

Google defines two levels of API access:

Level Description Requires:
Simple API calls do not access any private user data API key
Authorized API calls can read and write private user data, or the application's own data API key plus OAuth 2.0 credentials (different for different application types)

Getting access keys for your application

To get access keys, go to the Google APIs Console and specify your application's name and the Google APIs it will access. For simple access, Google generates an API key that uniquely identifies your application in its transactions with the Google Auth server.

For authorized access, you must also tell Google your website's protocol and domain. In return, Google generates a client ID. Your application submits this to the Google Auth server to get an OAuth 2.0 access token.

For detailed instructions for this process, see the Getting started page.

See below for details and examples of how to use these credentials in your application.

Simple access using the API key

The API key identifies your application for requests that don't require authorization.

Whether or not your application requires authorized access, your code should call setApiKey to pass in the value of your API key:

gapi.client.setApiKey(YOUR API KEY);

For a complete example of simple API access, follow this link.

Authorized access

To access a user's personal information, your application must work with Google's OAuth 2.0 mechanism.

OAuth 2.0 basics

You may want to start with this overview of Using OAUth 2.0 to Access Google APIs.

Behind the scenes, the OAuth 2.0 mechanism performs a complex operation to authenticate the user, the application, and the Google Auth server. The components of the JavaScript client library manage this process for you, so that all your code has to do is pass in the following objects:

  • The client ID you received when you registered your application
  • The scope object that specifies which data your application will use

About scope

The scope object defines the level of access to a particular API that your application will use. For more information about how scopes work, refer to this OAuth 2.0 documentation. The following example uses the syntax of the Google+ API to specify the Google+ profile of the currently logged-in user:

https://www.googleapis.com/auth/plus.me

OAuth 2.0 authorization flow

The JavaScript client library uses the OAuth 2.0 client-side flow for making requests that require authorization. If you would like to see what this looks like in action, check out Google's OAuth 2.0 Playground.

OAuth 2.0 authorization in the JavaScript client library proceeds as follows:

  1. The user clicks a "login" link.
  2. The browser shows a popup that allows the user to authenticate and authorize the web application.
  3. After successful authorization, the browser redirects the user back to the calling application (your application).
  4. The callback saves the authorization token and closes the popup.

After this, the application is authorized to access the user's personal data.

Auth example

This example code is adapted from authSample.html.

Specifying your client ID and scopes

This example starts by defining variables to hold the client ID, API key and scopes:

var clientId = 'YOUR CLIENT ID';
var apiKey = 'YOUR API KEY';
var scopes = 'https://www.googleapis.com/auth/plus.me';

Next, there are separate functions to set the API key, start the authorization process, and handle the result:


function handleClientLoad() {
  gapi.client.setApiKey(apiKey);
  window.setTimeout(checkAuth,1);
}

function checkAuth() {
  gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}

function handleAuthResult(authResult) {
  var authorizeButton = document.getElementById('authorize-button');
  if (authResult && !authResult.error) {
    authorizeButton.style.visibility = 'hidden';
    makeApiCall();
  } else {
    authorizeButton.style.visibility = '';
    authorizeButton.onclick = handleAuthClick;
  }
}

function handleAuthClick(event) {
  gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
  return false;
}

The handleClientLoad function is called when the JavaScript client library loads. It sets the API key and calls the checkAuth function.

When the user clicks on the Login button, a function called handleAuthClick (not defined in this snippet) calls the JavaScript client library's authorize method, passing in the client ID and the scope object. This function's callback is handleAuthResult.

If authorization succeeds, the Google auth server returns the auth token to the authorize function. (If authorization fails, an error message is returned.) The returned object is passed to handleAuthResult, the callback function.

handleAuthResult checks this returned object. If it is a valid token, the function hides the Login button and goes ahead with the API call.

Making the API request

In the code, an authenticated request looks exactly like an unauthenticated request. If the application has received an OAuth 2.0 token, the JavaScript client library includes it in the request automatically. This code completes the process started in the previous example:

function makeApiCall() {
  gapi.client.load('plus', 'v1').then(function() {
    var request = gapi.client.plus.people.get({
        'userId': 'me'
          });
    request.then(function(resp) {
      var heading = document.createElement('h4');
      var image = document.createElement('img');
      image.src = resp.result.image.url;
      heading.appendChild(image);
      heading.appendChild(document.createTextNode(resp.result.displayName));

      document.getElementById('content').appendChild(heading);
    }, function(reason) {
      console.log('Error: ' + reason.result.error.message);
    });
  });
}
  

The first line of this function loads the API for the Google+ service. The next line initializes a request object using the syntax of the Google+ API (people references the Google+ "People" resource; me is a keyword that specifies the currently logged-in user). The third line executes the request, and displays the result on the web page.

Making a request with CORS

To make an authenticated CORS request, you can add the OAuth 2.0 access token to the request header or add it as a URL parameter. For details, read the CORS documentation.

The standalone auth client

Your application can also use a subset of the full JavaScript client library that performs authentication and nothing else. It includes only the gapi.auth methods.

Use the standalone auth client in web applications that will run in environments with full CORS support, such as Chrome extensions and mobile browsers. If your application may run on browsers which do not support CORS, or if you want to use other features of the JavaScript library, use the standard JavaScript client.

For information about how to load and use the auth client, see the CORS documentation.