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
4 . And make new project by clicking this
5 . Input your project name and Location (Optional)
6 . Open the notification and select your project
7 . Click this to go to the API page
8 . On the Api & Services click “Enable APIs and services” button
9 . Click “Credentials” in the sidebar and click “Configure consent screen”
10 . After you click “Configure consent screen” then on this page click button “Get started”
11 . Input your “App name” and “User support email” and click “Next”
12 . Select “Internal” or “External” and click “Next”
13 . Input your email in “Contact Information” and click “Next”
14 . Checked the agreement and click “Continue”
15 . Click “Create” to create the project
16 . In Oauth Overview click “Create OAuth Client”
17 . In “Application Type” select “Web application”
18 . Input “Name”, “Authorized Javascript Origin”, and “Authorized redirect URIs”. I personally use localhost:3000. Authorized redirect URIs used for url after login.
19 . It will show you the image, you will get client Id, client secret by click copy icon or download JSON
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
21 . It will show a scope option. I personally select “…/auth/userinfo.email”, “…/auth/userinfo.profile”, and “openid”
22 . Click “Update”
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