Ad

How Can I Use The Google OAuth2 ID Token With Node.js / Passport.js To Verify If The User Is Valid And Authenticated?

On my front end, I'm using vue.js (not that that matters) and with the Google OAuth flow, I get back an id_token from:

let googleAuthIdToken = await this.auth2.currentUser
            .get()
            .getAuthResponse().id_token;

I want to then pass that token to my node.js server (Express / Passport) to verify that the user is allowed to login.

I want to use passport and send back a JWT to the front end in my response.

Can someone please guide me as to how to accomplish this?

Ad

Answer

It is easier to make use of a node module called googleapis, After installation, import the module.

import { google } from 'googleapis';

Then you need to create an OAuthClient by specifying the CLIENT_ID, CLIENT_SECRET, REDIRECT_URL.

const oauth2Client = new google.auth.OAuth2(
    CLIENT_ID,
    CLIENT_SECRET,
    REDIRECT_URL,
);

Then you can get the token from google by using the oauth2Client.

const {tokens} = await oauth2Client.getToken(code);
oauth2Client.setCredentials(tokens);

Inorder to obtain the neccessary user information to store in your own database, You need to call this method.

const plus = google.plus({ version: 'v1', oauth2Client });
const me = await plus.people.get({ userId: 'me' });

me will contain the user information that you are looking for, once you obtain the user information you can then store it using passport js.

Ad
source: stackoverflow.com
Ad