Verifying JWT Tokens

When to verify JWT Tokens?

In every API call to your backend server, you should include the access_token in the header of your requests. You need to verify the access_token on each endpoint that you deem necessary. Usually, you would use a middleware so it automatically handles the verification for each of your routes.

Some good JWT middleware libraries that you can use:

Verifying JWT Using Cotter's Node.js Library

Installation

yarn add cotter

Use Cotter's validator function to validate the JWT Token.

import { CotterValidateJWT } from "cotter";
โ€‹
try {
var valid = await CotterValidateJWT(token);
} catch (e) {
console.log(e);
}

Third-Party JWT Libraries to Verify the Tokens

You can use third party libraries to verify JWT tokens. Check the list of third party libraries here. Make sure you check for a โœ…for the algorithm that the JWT token uses.

For Cotter's JWT Tokens, use:

  • Algorithm: ES256

  • Public Keys: https://www.cotter.app/api/v0/token/jwks

    • take the key with kid = SPACE_JWT_PUBLIC:8028AAA3-EC2D-4BAA-BE7A-7C8359CCB9F9

    • Make sure you take the keys from this endpoint, and cache when necessary, but don't hard-code it. The key may change.

How to Verify the Access Token

  1. Make sure that the token is not expired

  2. Make sure that the aud matches your API_KEY_ID

  3. Check the authentication_method and scopes to match your API requirements (scopes are default to access for now, and cannot be changed).

  4. Check that the JWT is well formed.

  5. Check the signature.