Search code examples
node.jsexpressjwtpassport.jsgoogle-oauth

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?


Solution

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