Login using Google

What You'll Need

Backbench account - Sign Up, the personal account will always remain free to use.

Google Developer account - Sign In and create a project on Google developers.

Demo

Prerequisites for the app

  1. After you’re done creating a project in google console, in the sidebar under "APIs & Services", select Credentials, and navigate to the OAuth consent screen tab. Choose an Email Address, specify Application Name, provide Authorized Domain (input backbench.io for now) and press Save.

  2. In the Credentials tab, select the Create credentials drop-down list, and choose OAuth client ID.

  3. Under Application type, select Web application. Register the origins from which your app is allowed to access the Google APIs, as follows(An origin is a unique combination of protocol, hostname, and port).

  4. In the Authorized JavaScript origins field, enter the origin for your app. You can paste the base URL of the app (in endpoint section).

  5. The Authorized redirect URI field, enter a valid redirect URI for login (This is the URI, where you'll be redirecting after successful sign in to google) for time being, you can suffix the above base URL with /google, then click on Create button.

Note: Copy your Client ID and Client Secret for further use.

Frontend

  1. Select +, in the upper right corner of file manager to create a html file . For example, say "google.html" and select CREATE or hit Enter.

  2. Copy and paste the code module from below.

  3. Replace CLIENT_ID (from Google Cloud Console)and REDIRECT_URI (from backbench endpoint) in href link.

  4. Select save.

<!doctype html>
<head>
</Head>
<body>
<h1> login using Google</h1><br><br>
<a href="https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.googleapis.com/auth/userinfo.profile&access_type=offline&include_granted_scopes=true&redirect_uri=REDIRECT_URI&response_type=code&client_id=CLIENT_ID">Login using google</a>
</body>
</html>

Note: Do not forget to enable File Manager from Endpoints section.

Backend

  1. Create a module login.js for Node.js andlogin for BBLANG.

  2. Replace CLIENT_ID ( found in Google Credentials screen ), Client_Secret( found in Google Credentials screen ), and REDIRECT_URI ( from Backbench Endpoint ) in the code.

  3. Select save.

const request = require("request");
module.exports.endpoint = function(req, cb) {
 request.post(
  "https://www.googleapis.com/oauth2/v4/token?client_id=CLIENT_ID&client_secret=CLIENT_Secret&redirect_uri=REDIRECT_URI&client_type:private&grant_type=authorization_code&code=" +
   req.query.code,
  function(error, response, body) {
   if (error) {
    cb({ code: error });
   } else {
    var token = JSON.parse(response.body).access_token;
    request(
     "https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token,
     function(error, response, body) {
      if (error) {
       cb({ code: error });
      } else {
       var info = JSON.parse(body);
       bb.log(info.name + " logged in!");
       cb(undefined, { access_token: token, code: JSON.parse(response.body) });
      }
     }
    );
   }
  }
 );
};

For Node.js, map login.js module to /login and for BBLANG, map google:login to /login in Endpoints section.

For Node.js App:

  1. Select +, in the upper right corner to create a Module. For example, say "package.json" and select CREATE or hit Enter.

  2. Copy and paste the code module from below.

{
    "dependencies": { 
        "request": "^2.88.0"
    }
}

A package.json file lists the packages that your project depends on. allows you to specify the versions of a package that your project can use using semantic versioning rules.

Logging in

  1. Google's OAuth 2.0 endpoint is at https://accounts.google.com/o/oauth2/v2/auth. This endpoint is accessible only over HTTPS (The implementation is shown in Frontend section).

  2. The Google authorization server supports several query string parameters for web server applications, some of them which is mandatory are:

    1. client_id: The client ID for your application. You can find this value in the Credentials screen.

    2. redirect_uri: Determines where the API server redirects the user after the user completes the authorization flow. The value must exactly match one of the redirect_uri values listed for your project in the API Console. Note that the http or https scheme, case, and trailing slash ('/') must all match.

    3. scope: 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. There are other optional parameters also (refer: https://developers.google.com/identity/protocols/OAuth2WebServer#incrementalAuth).

User Permission

In the OAuth 2.0 protocol, your app requests authorization to access resources, which are identified by scopes. It is considered a best user-experience practice to request authorization for resources at the time you need them. To enable that practice, Google's authorization server supports incremental authorization. This feature lets you request scopes as they are needed and, if the user grants permission, add those scopes to your existing access token for that 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. Document provides a full list of scopes that you might use to access Google APIs (https://developers.google.com/identity/protocols/googlescopes).

Sample redirect to Google's authorization server:

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https://www.googleapis.com/auth/userinfo.profile&
 access_type=offline&
 include_granted_scopes=true&
 state=state_parameter_passthrough_value&
 redirect_uri=http%3A%2F%2Foauth2.example.com%2Fcallback&
 response_type=code&
 client_id=client_id

After the web server receives the authorization code, it can exchange the authorization code for an access token.

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

  • code: The authorization code returned from the initial request.

  • client_id: The client ID obtained from the Credentials screen.

  • client_secret: The client secret obtained from the API Console.

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

Sample request:

post https://www.googleapis.com/oauth2/v4/token?
  client_id=client_id
  &client_secret=client_secret
  &redirect_uri=http%3A%2F%2Foauth2.example.com%2Fcallback
  &client_type: private
  &grant_type=authorization_code
  &code={The authorization code returned from the initial request}

Confirming Identity

To implement incremental authorization, you complete the normal flow for requesting an access token but make sure that the authorization request includes previously granted scopes. This approach allows your app to avoid having to manage multiple access tokens.

The code samples below also show the code that you need to add to use incremental authorization:

https://www.googleapis.com/oauth2/v2/userinfo?access_token=<access_token>

Last updated