Testing out authentication in your application is crucial. When integrating with Auth0 it becomes more difficult. You aren’t able to generate the tokens you want. There is rate limiting involved for their API. It’s also not something they should be concerned with. Your implementation should be handled by yourself.

For unit testing to be quick we should be able to rapidly spin up valid tokens, invalid tokens, expired tokens, etc to test out our authentication layer. One handy library for this is mock-jwks.

This will mock calls to the JWK well knowns endpoint, as well as manage signing and generating the tokens for us. Basically it will pretend to be Auth0 for us

For this tutorial we’ll also assume to use babel so we can do stuff like use import.

Read more about why RS256 and using JWKs is better than just random signing keys https://auth0.com/blog/navigating-rs256-and-jwks/

Code to Verify JWT

First lets setup the code that checks if the token is valid. We’ll need the jsonwebtoken library and jwks-rsa library. Both are from Auth0.

yarn add jsonwebtoken jwks-rsa

We’ll import and create a jwksClient. We will then provide it our url for our applications JWKS. This is the url that will have our signing keys to verify that a token is from the proper Auth0 app but not provide private keys that allow new tokens to be signed.

import jwt from "jsonwebtoken";
import jwksClient from "jwks-rsa";

const client = jwksClient({
  jwksUri: "https://MYAUTH0APP.auth0.com/.well-known/jwks.json",
});

You may have something along these lines. We will need our jwt.verify call to be asynchronous as we will need to load up the JWKS. Rather than use callbacks we wrap it in a promise so we can easily work with async/await.

We receive a token to verify, a getKey callback which we’ll hear about in a second, and then we provide our algorithm, and a callback to deal with the returned error or decoded token.

export const verifyAuth0Token = async token => {
  return new Promise((resolve, reject) => {
    jwt.verify(token, getKey, { algorithms: ["RS256"] }, (err, decoded) => {
      if (err) {
        reject(err);
        return;
      }

      resolve(decoded);
    });
  });
};

The getKey is a function that the jsonwebtoken library will call with a header, and a callback to tell it that we failed, or successfully loaded up the signing key.

Using our jwks-rsa library we ask it to go retrieve our signing key for a specific kid. The kid is a unique identifier for the key. The jwks.json that we load from Auth0 will have a matching signing key for our kid. So we need the kid to know which key to use to check if our token is valid.

#testing #coding #codedaily #auth0

Unit Test Token Verification for Auth0 using Jest and mock-jwks
4.95 GEEK