Struggling to verify a JWT token in Node.js

433 views Asked by At

Please bear with me as I'm new to JWT and find it terribly confusing.

I have an Auth0-provided JWT which I need to verify. I'm using jose. Here's what I have:

const {payload, protectedHeader} = await jose.jwtVerify(
    token,
    secret,
    {algorithms: ['RS256']}
);

...where token is the JWT passed from my front-end to my back-end, and secret is my application secret (Auth0 > Applications > Settings.)

When run, this yields:

Key for the RS256 algorithm must be of type CryptoKey.

I read on Auth0 somewhere that RS256 JWTs must be verified with a private signing key. Not really knowing what this means, and because Auth0 also says that HS256 can be verified with the secret, I changed my signing algorithm to HS256. When I run the above, I then get:

"alg" (Algorithm) Header Parameter value not allowed

Any help here is hugely appreciated. I'm going round in circles.

1

There are 1 answers

3
Gary Archer On BEST ANSWER

To verify the JWT a token signing public key is needed. Usually code like this is used, to download it from the authorization server's JWKS endpoint.

import {createRemoteJWKSet, jwtVerify, JWTPayload} from 'jose';

const jwksUri = 'https://login.example.com/jwks';
const jwks = createRemoteJWKSet(new URI(jwksUri));

async function validateJWT(accessToken: string): Promise<JwtPayload> {

  const options = {
    algorithms: ['RS256'],
    issuer: 'myissuer',
    audience: 'myaudience'
  };

  const result = await jwtVerify(accessToken, jwks, options);
  return result.payload
}

Note that you must use an asymmetric signing algorithm. This enables any API or client to validate JWTs (with the public key), while only the authorization server can issue them (with the private key). More info in my blog post.

WORKING CODE

You can run this web and API example if you follow the README instructions and maybe compare the code against your own.