> For the complete documentation index, see [llms.txt](https://backbench.gitbook.io/backbench-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://backbench.gitbook.io/backbench-docs/3rd-party-integrations/login-using-google.md).

# Login using Google

## What You'll Need <a href="#what-youll-need" id="what-youll-need"></a>

Backbench account - [Sign Up](https://bench.backbench.io/signup), the personal account will always remain free to use.

Google Developer account - Sign In and create a project on [Google developers](https://console.developers.google.com.).

## Demo <a href="#prerequisites-for-sample-app" id="prerequisites-for-sample-app"></a>

{% embed url="<https://mybench-samples.backbench.io/google.html>" %}
Node.js Sample
{% endembed %}

{% embed url="<https://mybench-bbsamples.backbench.io/google.html>" %}
BBLANG Sample
{% endembed %}

## Prerequisites for the app <a href="#prerequisites-for-sample-app" id="prerequisites-for-sample-app"></a>

1. &#x20;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. &#x20;In the **Credentials** tab, select the **Create credentials** drop-down list, and choose **OAuth client ID**.
3. &#x20;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.&#x20;

## Frontend <a href="#frontend-1" id="frontend-1"></a>

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 <a href="#backend" id="backend"></a>

1. Create a module `login.js` for Node.js and`login` 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.

{% tabs %}
{% tab title="Node.js" %}

```javascript
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) });
      }
     }
    );
   }
  }
 );
};
```

{% endtab %}

{% tab title="BBLANG" %}

```javascript
google:callback(req)->{
    res = bb:http: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)
    
    access_token = std:parse(res.body).access_token //Token - can be saved for authentication
    
    bb:http:get("https://www.googleapis.com/oauth2/v2/userinfo?access_token="+access_token) //User details
};
```

{% endtab %}
{% endtabs %}

&#x20;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.

```javascript
{
    "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 <a href="#frontend" id="frontend"></a>

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:

```markup
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:

```http
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:

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