In this lesson, you will learn how to verify that a Bearer token received from an identity provider (IdP) like Auth0 or Okta is authentic and hasn't been tampered with.
When a client sends an Authorization: Bearer <token> header, your Node.js server cannot trust the token’s contents blindly. Since these tokens are JSON Web Tokens (JWTs), they use cryptographic signatures. To validate them, you must verify the signature using the IdP's Public Key.
Fetching the Public Key
IdPs publish their public keys at a standard endpoint, usually located at /.well-known/jwks.json. This is known as a JSON Web Key Set (JWKS). Instead of hardcoding keys, your server should fetch these keys dynamically so that when the IdP rotates their signing keys, your application doesn't break.
Verification Logic
Verification involves three critical steps:
- Signature Validation: Confirm the token was signed by the IdP's private key by matching it against the public key from the JWKS.
- Issuer Check (
iss): Ensure theissclaim matches your trusted IdP's domain. - Audience Check (
aud): Ensure theaudclaim matches your application's unique Client ID, preventing a token intended for another service from being used on yours.
Here is how you might implement this using a standard validation library:
const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');
const client = jwksClient({
jwksUri: 'https://your-auth-provider.com/.well-known/jwks.json'
});
function getKey(header, callback) {
client.getSigningKey(header.kid, (err, key) => {
callback(null, key.getPublicKey());
});
}
// In your middleware:
jwt.verify(token, getKey, { audience: 'your-client-id', issuer: 'https://your-auth-provider.com/' }, (err, decoded) => {
if (err) return res.status(401).send('Invalid Token');
req.user = decoded;
next();
});
By verifying the signature against the JWKS and checking the iss and aud claims, you ensure that the bearer token is genuine, intended for your application, and currently valid according to the identity provider that issued it.
Key Takeaway: Never accept a bearer token without verifying its digital signature against the issuer's published public keys and validating the standard identity claims.