Auth0 manual id_token validation with Node.js

Sachin Joshi
1 min readFeb 19, 2022

You may have a use case where you might want to validate the id_token of auth0 manually. I had a situation where Auth0 was used partially and had to be integrated into the existing auth system.

If you do a quick search about how to validate the id_token received from auth0 callback then you will probably not find it. There are npm packages that you can use express as a middleware that will do the validation. And that is the most common way one will use it. Check the link below

https://github.com/auth0/node-jwks-rsa/tree/61b5740b3846f74fa6d631be6712405700d9c163/examples/express-demo

But we want to check it manually. So to start, install 2 npm packages.

npm install jwks-rsa jsonwebtoken

Check the code below.

const jwksClient = require('jwks-rsa');
const jwt = require('jsonwebtoken');
const config = {
auth0: {
domain: <replace-me>,
client_id: <replace-me>,
},
};
async function decodeAndVerifyToken(token) {
const client = jwksClient({
jwksUri: `https://${config.auth0.domain}/.well-known/jwks.json`,
});
const kid = getKid(token);
const key = await getSigningKey(client, kid);
const signingKey = key.getPublicKey();
return jwt.verify(token, signingKey, {
audience: config.auth0.client_id,
issuer: `https://${config.auth0.domain}/`,
});
}
function getKid(token) {
const decodedToken = jwt.decode(token, { complete: true });
if (!decodedToken) {
throw new Error('Invalid token');
}
return decodedToken.header.kid;
}
function getSigningKey(client, kid) {
return new Promise((resolve, reject) => {
client.getSigningKey(kid, (err, res) => {
if (err) {
reject(err);
}
resolve(res);
});
});
}

--

--