0

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 
});
joafeldmann
  • 246
  • 4
  • 14

2 Answers2

0

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.

Community
  • 1
  • 1
Robert Rossmann
  • 11,931
  • 4
  • 42
  • 73
  • So there is no method for decoding the JWT included in the google-api-nodejs-client lib? – joafeldmann Dec 11 '14 at 09:04
  • They use the [gapitoken](https://github.com/bsphere/node-gapitoken) module to create the signature which, by inspecting the source, does not include decoding capabilities. You will have to install a separate module for this (or code something yourself!). – Robert Rossmann Dec 11 '14 at 09:07
0

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.

khelkun
  • 159
  • 1
  • 13