Search code examples
node.jsoauth-2.0google-api-nodejs-client

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 
});

Solution

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