OAuth 2.0 for Client-side Web Applications

Client Web application for OAuth 2.0

This article describes how to authorize access to Google's API from OAuth 2.0 implemented by a JavaScript Web application. OAuth 2.0 allows users to share specific data and applications while maintaining their user names, passwords and other private information. For example, applications can use OAuth 2.0 to obtain licenses from users to store files on their Google drives.

This OAuth 2.0 user traffic is called implicit subsidy flow. It is designed for application access API only when the user exists in the application. These applications are not confidential information that can be stored.

In this process, your application opens a Google URL and uses query parameters to determine the type of application your application and API need to access. You can open the URL in the current browser window or pop-up. Users can be authenticated by Google and granted the required permissions. Google then redirects users back to your application. Redirect the access token contained, verify your application, and then use the make API request.

Note: due to the security risks of correct execution, we strongly recommend that you use OAuth 2.0 library when interacting with Google's OAuth 2.0 endpoint. It is a best practice to take advantage of carefully debugged code provided by others, which will help protect you and your users. See the tabs in this document of JS client library as an example to illustrate how to authorize users to use Google API client JavaScript library.

precondition

Enable API for project

Applications that call Google APIs need to enable the API console. To be able to the appropriate API for your project:

  1. open library API console page for.
  2. Select an application related item. Create a project if you don't have one.
  3. Using the library page, find the API that each application will use. Click on each API and enable it for your project.

Create authorization certificate

Any application that uses OAuth 2.0 to access Google's API must have an OAuth 2.0 server authorization certificate that identifies the application to Google. The following steps describe how to create credentials for a project. Your application can then use credentials to access the API, which you have enabled for the project.

  1. open Certificate page API console inch
  2. Click Create credential > OAuth client ID.
  3. Complete the form. Set the application type Web application. For applications using JavaScript, all API requests authorized by Google must specify the authorized javascript source. Origin identifies the domain that can send API requests from your application.

Determine access scope

Scope enables your application to request access only to the number of resources they grant to your application that need while also enabling users to control access. Therefore, it is possible that there is an inverse relationship between the number of requested ranges and the possibility of obtaining user consent.

Before you start implementing OAuth 2.0 authorization, we recommend that you identify the scope where your application will need access rights.

Should OAuth 2.0 API scope The documentation contains a full list of the API s that you can use to access Google.

If your public application uses scope to allow access to some user data, it must complete the authentication process. If you see an unverified application testing your application on the screen, you must submit a verification request to delete it. Learn more about Unauthenticated applications , and get the answer Frequently asked questions about application validation At the help center.

OAuth 2.0 access token obtained

The following steps show how to interact with Google's OAuth 2.0 server application to obtain the user's consent to execute API requests on behalf of the user. Your application must be licensed before it can execute API requests that require user authorization.

Step 1: configure the customer object

If you are using Google's API client JavaScript library to handle OAuth 2.0 processes, the first step is to configure GAPI Auth2 and GAPI Client object. These objects enable applications to obtain user authorization and API requests for authorization.

The customer object identifies the scope of access your application requests allow. These values inform the consent screen, which Google displays to the user. stay Select access range The section provides information on how to determine which scoped applications should be allowed access upon request.

JS Client Library OAuth 2.0 user endpoint

The JavaScript client library simplifies many aspects of the authorization process:

  1. It can redirect the URL for Google's authorization server and provide a method to guide users to the URL.
  2. It handles redirects returned from the server to your application.
  3. It validates the access token returned by the authorization server.
  4. It stores the token that the authorization server sends to your application and retrieves it when your application then lets the authorized API call access.

The following code snippet is an excerpt from Complete example Shown later in this document. This code initializes the GAPI Client object, which your application will use later to make API calls. When creating objects, the GAPI The auth2 object, used by your application to check and monitor the user's authorization status, is also initialized.

To call GAPI client. Init specifies the following fields:

  • The apiKey and clientId values are used to specify the authorization certificate of the application. As discussed Create authorization credentials Section, you can obtain these values in the API console. Note that clientId is required if your application makes an API request for authorization. Applications that only allow unauthorized requests only need to specify an API key.
  • The scope field specifies a space delimited list Access scope The corresponding resources that your application needs to access. These values inform the consent screen, which Google displays to the user. We recommend to authorize your application to request access to the context scope whenever possible. In the case of accessing user data by request, through Incremental authorization , you help users more easily understand why your application needs requested access.
  • This discoveryDocs field identifies the list API discovered files , your application uses. A discovery document describes the surface API, including its resource schema and JavaScript client library. This information is used to generate methods that applications can use. In this example, the code retrieves the discovery document of Google cloud hard disk API version 3.

After GAPI client. After the init call is completed, the code will use the Google auth variable to identify the Google authentication object. Finally, the code will call a function listener when the user's login status changes. (this function is not defined in the code snippet.)

var GoogleAuth; // Google Auth object.
function initClient() {
  gapi.client.init({
      'apiKey': 'YOUR_API_KEY',
      'clientId': 'YOUR_CLIENT_ID',
      'scope': 'https://www.googleapis.com/auth/drive.metadata.readonly',
      'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
  }).then(function () {
      GoogleAuth = gapi.auth2.getAuthInstance();

      // Listen for sign-in state changes.
      GoogleAuth.isSignedIn.listen(updateSigninStatus);
  });
}

Step 2: redirect to Google's OAuth 2.0 server

Request the user data allowed to access and redirect the user to Google's OAuth 2.0 server.

JS Client Library OAuth 2.0 user endpoint

Call Google auth The signin () method directs the user to Google's authorization server.

GoogleAuth.signIn();

In practice, your application may set a Boolean value to determine whether to call signIn() before trying to call the API method.

The following code snippet demonstrates how to start the user authorization process. Note the following about code snippets:

var isAuthorized;
var currentApiRequest;

/**
 * Store the request details. Then check to determine whether the user
 * has authorized the application.
 *   - If the user has granted access, make the API request.
 *   - If the user has not granted access, initiate the sign-in flow.
 */
function sendAuthorizedApiRequest(requestDetails) {
  currentApiRequest = requestDetails;
  if (isAuthorized) {
    // Make API request
    // gapi.client.request(requestDetails)

    // Reset currentApiRequest variable.
    currentApiRequest = {};
  } else {
    GoogleAuth.signIn();
  }
}

/**
 * Listener called when user completes auth flow. If the currentApiRequest
 * variable is set, then the user was prompted to authorize the application
 * before the request executed. In that case, proceed with that API request.
 */
function updateSigninStatus(isSignedIn) {
  if (isSignedIn) {
    isAuthorized = true;
    if (currentApiRequest) {
      sendAuthorizedApiRequest(currentApiRequest);
    }
  } else {
    isAuthorized = false;
  }
}

Step 3: Google will prompt the user for consent

In this step, the user will decide whether to give your application the requested access. At this stage, Google will display a window of consent that displays the name of your application and the Google API service, which requests permission to access with the user's authorization credentials. Users can then agree or deny access to your application.

Your application does not need to do anything at this stage because it waits for an OAuth 2.0 server from Google to indicate whether access is granted to respond. The response is described in the following steps.

Step 4: process OAuth 2.0 server response

JS Client Library OAuth 2.0 user endpoint

The JavaScript client library processes responses from Google's authorization server. If a listener is set to monitor the current user's change of login status, this function is called when the user grants the application requesting access.

Called Google's API

JS Client Library OAuth 2.0 user endpoint

After your application gets an access token, you can use the JavaScript client library to make API requests on behalf of users. The client library manages tokens for your access, and you don't need to do anything special when sending requests.

The client library supports two ways to call API methods. If you load a discovery document, the API will define your methods and specific functions. You can also use this gapi.client.request Function to call the API method. The following two clips demonstrate the about. Of the driver API for these options Get method.

// Example 1: Use method-specific function
var request = gapi.client.drive.about.get({'fields': 'user'});

// Execute the API request.
request.execute(function(response) {
  console.log(response);
});


// Example 2: Use gapi.client.request(args) function
var request = gapi.client.request({
  'method': 'GET',
  'path': '/drive/v3/about',
  'params': {'fields': 'user'}
});
// Execute the API request.
request.execute(function(response) {
  console.log(response);
});

Complete example

JS Client Library OAuth 2.0 user endpoint

Sample code demonstration

This section contains the following proof code examples to demonstrate how the code behaves in real applications. After you authorize the application, it will be listed in it Apps connected to your Google account . This application is called OAuth 2.0. Users demonstrate Google API documents. Similarly, if you cancel the visit and refresh the page, the application will no longer be listed.

Note that this application requests access https://www.googleapis.com/auth/drive.metadata.readonly Range. This access request is just to demonstrate how to start the OAuth 2.0 stream in a JavaScript application. This application does not make any API requests.

Code example of JavaScript

As shown above, this code example is a page (an application) that loads Google API client library JavaScript and initiates OAuth 2.0 flow. This page displays two:

  • A button that allows the user to log in to the application. If the user has not previously authorized the application, then the application starts the OAuth 2.0 stream.
  • Two buttons that allow the user to either log out of the application or revoke previously granted access to the application. If your application exits, you have not revoked the access granted to the application. Before you need to log in again, the application can request other authorization in its own name, but you won't have the application you use. You can grant access again next time. However, if you cancel access, you need to grant access again.

You can also revoke access to the application through Permissions for Page for your Google account. The application is listed as OAuth 2.0 users to demonstrate Google API documents.

<script>
  var GoogleAuth;
  var SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly';
  function handleClientLoad() {
    // Load the API's client and auth2 modules.
    // Call the initClient function after the modules load.
    gapi.load('client:auth2', initClient);
  }

  function initClient() {
    // Retrieve the discovery document for version 3 of Google Drive API.
    // In practice, your app can retrieve one or more discovery documents.
    var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';

    // Initialize the gapi.client object, which app uses to make API requests.
    // Get API key and client ID from API Console.
    // 'scope' field specifies space-delimited list of access scopes.
    gapi.client.init({
        'apiKey': 'YOUR_API_KEY',
        'discoveryDocs': [discoveryUrl],
        'clientId': 'YOUR_CLIENT_ID',
        'scope': SCOPE
    }).then(function () {
      GoogleAuth = gapi.auth2.getAuthInstance();

      // Listen for sign-in state changes.
      GoogleAuth.isSignedIn.listen(updateSigninStatus);

      // Handle initial sign-in state. (Determine if user is already signed in.)
      var user = GoogleAuth.currentUser.get();
      setSigninStatus();

      // Call handleAuthClick function when user clicks on
      //      "Sign In/Authorize" button.
      $('#sign-in-or-out-button').click(function() {
        handleAuthClick();
      }); 
      $('#revoke-access-button').click(function() {
        revokeAccess();
      }); 
    });
  }

  function handleAuthClick() {
    if (GoogleAuth.isSignedIn.get()) {
      // User is authorized and has clicked 'Sign out' button.
      GoogleAuth.signOut();
    } else {
      // User is not signed in. Start Google auth flow.
      GoogleAuth.signIn();
    }
  }

  function revokeAccess() {
    GoogleAuth.disconnect();
  }

  function setSigninStatus(isSignedIn) {
    var user = GoogleAuth.currentUser.get();
    var isAuthorized = user.hasGrantedScopes(SCOPE);
    if (isAuthorized) {
      $('#sign-in-or-out-button').html('Sign out');
      $('#revoke-access-button').css('display', 'inline-block');
      $('#auth-status').html('You are currently signed in and have granted ' +
          'access to this app.');
    } else {
      $('#sign-in-or-out-button').html('Sign In/Authorize');
      $('#revoke-access-button').css('display', 'none');
      $('#auth-status').html('You have not authorized this app or you are ' +
          'signed out.');
    }
  }

  function updateSigninStatus(isSignedIn) {
    setSigninStatus();
  }
</script>

<button id="sign-in-or-out-button"
        style="margin-left: 25px">Sign In/Authorize</button>
<button id="revoke-access-button"
        style="display: none; margin-left: 25px">Revoke access</button>

<div id="auth-status" style="display: inline; padding-left: 25px"></div><hr>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script async defer src="https://apis.google.com/js/api.js" 
        onload="this.onload=function(){};handleClientLoad()" 
        onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

Incremental authorization

In OAuth 2.0 protocol, your application requests authorized access to resources, which is determined by the scope. It is considered one of the best user experience practices to request authorization when you need their time resources. To achieve this, Google's authorization server supports incremental authorization. This feature allows you to request ranges when needed, and if the user grants permissions, these ranges are added to the token for the user's existing access.

For example, an application that allows people to sample music tracks and create mixes may require very few resources at the time of login than in the signatory's name. However, saving the finished mix requires access to their Google drive. Most people will feel natural if they are only asked to access their Google cloud app when they really need it.

In this case, the application at login may check in the required profile range to execute the basic, and then request it later https://www.googleapis.com/auth/drive.file The time range for saving the mix on the first request.

The following rules apply to obtaining an access token from incremental authorization:

  • The token can be used to access resources corresponding to any new combination authorization scope rolled in.
  • When you use the federated authorization of a token to obtain an access token, the token represents the federated authorization and can use any range of access refresh.
  • Portfolio authorization includes all ranges of API projects granted by users, even if they are required to allocate funds from different customers. For example, if a user uses the desktop client of one application to grant access to one scope through a mobile client, and then gives another application with the same scope, the authorization to be merged will include the scope.
  • If the revocation token represents the joint authorization, the scope of access to all authorizations represents the simultaneous revocation of relevant users.

The following code example shows how to add a scope to an existing access token. This approach allows your application to avoid the need to manage multiple access tokens.

JS Client Library OAuth 2.0 user endpoint

To add the scope to an existing access token, call the Google user Grant (options) method. The options object identifies additional scopes to grant access to.

// Space-separated list of additional scope(s) you are requesting access to.
// This code adds read-only access to the user's calendars via the Calendar API.
var NEW_SCOPES = 'https://www.googleapis.com/auth/calendar.readonly';

// Retrieve the GoogleUser object for the current user.
var GoogleUser = GoogleAuth.currentUser.get();
GoogleUser.grant({'scope': NEW_SCOPES});

Revocation token

In some cases, the user may want to revoke access to the application. Users can access by revoking access Account settings . You can also programmatically revoke access to an application. Programming Undo is important in case the user unsubscribes or deletes the application. In other words, an API request may be included as part of the removal process to ensure that the permission to license the application is removed.

JS Client Library OAuth 2.0 user endpoint

To programmatically revoke a token, call GoogleAuth.disconnect():

GoogleAuth . Disconnect ();

Added by eatadi on Mon, 24 Jan 2022 12:07:38 +0200