Google Oauth 2.0 in Node JS



This content originally appeared on DEV Community and was authored by fauzihazim

I write on Medium as a personal reference—to revisit my ideas whenever I’m working on a new project or building something. Here is how to integrate Google oauth 2.0 especially in Node JS.

1 . Open https://console.cloud.google.com/
2 . login to your Gmail
3 . Click this
Google Oauth2.0 in Node JS
4 . And make new project by clicking this
Google Oauth2.0 in Node JS
5 . Input your project name and Location (Optional)
Google Oauth2.0 in Node JS
6 . Open the notification and select your project
Google Oauth2.0 in Node JS

7 . Click this to go to the API page
Google Oauth2.0 in Node JS

8 . On the Api & Services click “Enable APIs and services” button
Google Oauth2.0 in Node JS

9 . Click “Credentials” in the sidebar and click “Configure consent screen”
Google Oauth2.0 in Node JS

10 . After you click “Configure consent screen” then on this page click button “Get started”

Google Oauth2.0 in Node JS

11 . Input your “App name” and “User support email” and click “Next”

Google Oauth2.0 in Node JS

12 . Select “Internal” or “External” and click “Next”

Google Oauth2.0 in Node JS

13 . Input your email in “Contact Information” and click “Next”

Google Oauth2.0 in Node JS

14 . Checked the agreement and click “Continue”

Google Oauth2.0 in Node JS

15 . Click “Create” to create the project

Google Oauth2.0 in Node JS

16 . In Oauth Overview click “Create OAuth Client”

Google Oauth2.0 in Node JS

17 . In “Application Type” select “Web application”

Google Oauth2.0 in Node JS
Google Oauth2.0 in Node JS

18 . Input “Name”, “Authorized Javascript Origin”, and “Authorized redirect URIs”. I personally use localhost:3000. Authorized redirect URIs used for url after login.

Google Oauth2.0 in Node JS

19 . It will show you the image, you will get client Id, client secret by click copy icon or download JSON

Google Oauth2.0 in Node JS
Copy that on .env file. Example

YOUR_CLIENT_ID = paste-your-Client-Id-here
YOUR_CLIENT_SECRET = paste-your-Client-Id-secret
YOUR_REDIRECT_URL = paste-your-redirect-URL-here

20 . Click “Data Access” and “Add or remove scopes” to show Scope Option

Google Oauth2.0 in Node JS

21 . It will show a scope option. I personally select “…/auth/userinfo.email”, “…/auth/userinfo.profile”, and “openid”

Google Oauth2.0 in Node JS

22 . Click “Update”

Google Oauth2.0 in Node JS
23 . Execute “npm install googleapis crypto express express-session dotenv” in terminal project
24 . Copy this in your project.

import {google} from 'googleapis';
import crypto from 'crypto';
import express from 'express';
import session from 'express-session';
import 'dotenv/config';

const app = express();


/**
 * To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI
 * from the client_secret.json file. To get these credentials for your application, visit
 * https://console.cloud.google.com/apis/credentials.
 */
const oauth2Client = new google.auth.OAuth2(
  process.env.YOUR_CLIENT_ID,
  process.env.YOUR_CLIENT_SECRET,
  process.env.YOUR_REDIRECT_URL
);


// Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
const scopes = [
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile'
];


// Generate a secure random state value.
const state = crypto.randomBytes(32).toString('hex');


// Generate a url that asks permissions for the Drive activity and Google Calendar scope
const authorizationUrl = oauth2Client.generateAuthUrl({
  // 'online' (default) or 'offline' (gets refresh_token)
  access_type: 'offline',
  /** Pass in the scopes array defined above.
    * Alternatively, if only one scope is needed, you can pass a scope URL as a string */
  scope: scopes,
  // Enable incremental authorization. Recommended as a best practice.
  include_granted_scopes: true,
  // Include the state parameter to reduce the risk of CSRF attacks.
  state: state
});


app.get('/auth/google', (req, res) => {
    res.redirect(authorizationUrl);
})


// Callback
app.get("/login", async (req, res) => {     // Change login with your redirect url patch
    const {code} = req.query;
    const {tokens} = await oauth2Client.getToken(code);
    oauth2Client.setCredentials(tokens);
    const oauth2 = google.oauth2({
        auth: oauth2Client,
        version: 'v2'
    })
    const {data} = await oauth2.userinfo.get();
    res.send(data);
})

25 . I suggest using a newer version of googleapis or “googleapis”: “^149.0.0” rather than using “googleapis”: “^150.0.1”. Because I faced error in node_module

And make new project by clicking this


This content originally appeared on DEV Community and was authored by fauzihazim