joafeldmann
joafeldmann

Reputation: 246

google-api-nodejs-client / How to decode the id_token received from oauth2Client.getToken

How to decode the id_token received from oauth2Client.getToken to get access to the JWT JSON fields email, sub, ..? Is there a function included in the google-api-nodejs-client lib? In https://developers.google.com/accounts/docs/OpenIDConnect in says:

Since most API libraries combine the validation with the work of decoding the base64 and parsing the JSON, you will probably end up validating the token anyway as you access the fields in the ID token.

oauth2Client.getToken(req.query.code, function(err, tokens) {
    // how to decode tokens.id_token to get 
});

Upvotes: 0

Views: 1716

Answers (2)

khelkun
khelkun

Reputation: 197

here is the documentation

Just in case the Google documentation would be refactored in the future:

const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
  const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID,  // Specify the CLIENT_ID of the app that accesses the backend
      // Or, if multiple clients access the backend:
      //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
  });
  const payload = ticket.getPayload();
  const userid = payload['sub'];
  // If request specified a G Suite domain:
  // const domain = payload['hd'];
}
verify().catch(console.error);

Also available here

Note that I was using @googleapis/oauth2 instead of google-auth-library but I noticed @googleapis/oauth2:

[Deprecated] Obtains end-user authorization grants for use with other Google APIs. So I guess google-auth-library is the right choice.

Upvotes: 0

Robert Rossmann
Robert Rossmann

Reputation: 12149

According to RFC, the JSON Web Token, when encoded, is composed of three parts (each part being a base64-encoded JSON object), separated by dots:

  1. Header
  2. Actual data
  3. Signature

The header is pretty much a constant when used with Google APIs. You are going to need the second part.

To visualise this even better, take a look at jwt.io - it will show you the exact structure of the encoded token, in colours!:)

I recommend that you study carefully how it works, then install an npm module (there's aplenty around, search for jwt) to do the actual decoding for you.

Upvotes: 0

Related Questions