ANewGuyInTown
ANewGuyInTown

Reputation: 6437

How to verify google auth token at server side in node js?

My front end application is authenticated using gmail account.

I retrieve id_token after the authentication is successful and send it as Authorization Header as bearer token.

E.g. http://localhost:4000/api

Authorization Bearer token_id

At nodejs server side, I call the following method to verify the token.

exports.verifyUser = function(req, res, next) {
    var GoogleAuth = require('google-auth-library');
    var auth = new GoogleAuth();
    var client = new auth.OAuth2(config.passport.google.clientID, config.passport.google.clientSecret, config.passport.google.callbackURL);
    // check header or url parameters or post parameters for token
    var token = "";
    var tokenHeader = req.headers["authorization"];
    var items = tokenHeader.split(/[ ]+/);
    if (items.length > 1 && items[0].trim().toLowerCase() == "bearer") {
        token = items[1];
    }
    if (token) {
        var verifyToken = new Promise(function(resolve, reject) {
            client.verifyIdToken(
                token,
                config.passport.google.clientID,
                function(e, login) {
                    console.log(e);
                    if (login) {
                        var payload = login.getPayload();
                        var googleId = payload['sub'];
                        resolve(googleId);
                        next();
                    } else {
                        reject("invalid token");
                    }
                }
            )
        }).then(function(googleId) {
            res.send(googleId);
        }).catch(function(err) {
            res.send(err);
        })
    } else {
        res.send("Please pass token");
    }
}

When I call the above method, I always get Invalid token response with following error.

Error: No pem found for envelope:     {"alg":"RS256","kid":"c1ab5857066442ea01a01601
850770676460a712"}
    at OAuth2Client.verifySignedJwtWithCerts (\node_modules\google-auth-libr
ary\lib\auth\oauth2client.js:518:13)

Any help is highly appreciated.

Upvotes: 22

Views: 26065

Answers (4)

mhdyaseen8841
mhdyaseen8841

Reputation: 1

You can now able to validate google auth token simply using firebase.

first of all create file named firebase-config and store your firebase configurations (which is got from firebase settings).

imports these:

import { initializeApp } from 'firebase-admin/app';
import { getAuth  } from 'firebase-admin/auth';
import { firebaseConfig } from 'PATH_TO_CONFIG_FILE';  //(importing of your config file that you had created)

initialisation:

const defaultApp = initializeApp(firebaseConfig);

google token verify function:

async verifyGoogleId(token) {
      const auth = getAuth(defaultApp);
      const firebaseUser = await auth.verifyIdToken(token);

      if (!firebaseUser) {
         throw new error();
      }
}

Upvotes: 0

Khim Bahadur Gurung
Khim Bahadur Gurung

Reputation: 764

First of all, do not use Id_Token for authorization. It is only for authentication. Use access token for authorization. Use link below to verify token.

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=${access_token}

Upvotes: 2

Bertrand Martel
Bertrand Martel

Reputation: 45352

OAuth2Client.verifyIdToken take an idToken in arguments, from the library source :

/**
 * Verify id token is token by checking the certs and audience
 * @param {string} idToken ID Token.
 * @param {(string|Array.<string>)} audience The audience to verify against the ID Token
 * @param {function=} callback Callback supplying GoogleLogin if successful
 */
OAuth2Client.prototype.verifyIdToken = function(idToken, audience, callback)

You have passed the whole header value bearer eyJhbGciOiJSUzI1NiIsImtpZCI6ImMxYWI1OD U3MDY2NDQyZWEwMWEwMTYwMTg1MDc3MDY3NjQ2MGE3MTIifQ so you will have to split the headers value as :

var authorization = req.headers["authorization"];
var items = authorization.split(/[ ]+/);

if (items.length > 1 && items[0].trim() == "Bearer") {
    var token = items[1];
    console.log(token);
    // verify token
}

Is this the right approach to verify token ?

Yes, this is the right way to verify token. For debugging, you can also verify token with the tokeninfo endpoint if you have any doubt or for quick testing :

https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123
  • Do I send the id_token as Authorization bearer? Or is it for authorization only?
  • How do I send the id_token to the sever side? Thru url, header?

You can send JWT token in Authorization header but it could lead to usecase where you have multiple Authorization headers. It's best to URL encode or embed the token in the body. You can check Google example here

Moreover, the following are required by Google :

  • the token must be sent via HTTPS POST
  • the token integrity must be verified

To optimize your code, you could also move your Google auth object to your app.js at the root of your app instead of redefining it each time the token should be verified. In app.js :

var app = express();

var GoogleAuth = require('google-auth-library');
var auth = new GoogleAuth();
app.authClient = new auth.OAuth2(config.passport.google.clientID, config.passport.google.clientSecret, config.passport.google.callbackURL);

and in verifyUser call it from req.app.authClient :

req.app.authClient.verifyIdToken(...)

Upvotes: 14

xuesong zhu
xuesong zhu

Reputation: 49

I finally found the answer today. The Firebase tool will connect the native Google to the third-party login token, and then encapsulate another layer. The token obtained at this time is no longer the original token given to us by Google.

  • A1:
    • Original Token: GoogleDesignInAccount Account = Task.getResult(ApiException.class);
    • Account.getidToken () // This is the original token
  • B1:
    • Firebase token: FireBaseUser currentUser = Mauth.getCurrentUser ();
    • String token = currentUser.getIdToken(false).getResult().getToken();
  • A2:
    • Google officially provides a method to verify the token
  • B2:
    • Firebase officially provides the authentication token method

We use code names for the four data points above. If you need to verify the validity of tokens in the background, they must correspond to each other, A1 to A2 and B1 to B2. If you use A2 to validate the B1, it will fail

Upvotes: 0

Related Questions