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:

Don't have a backend server? Use the API.

How to Verify the Access Token

The access token is a JWT Token, and it's signed using Asymmetric Signing Algorithm ES256. This means, unlike symmetric JWT tokens that are signed and verified using the same secret key, this asymmetric JWT Token is signed using a secret key that only Cotter knows, but can be verified using a public key that you can find here.

Checking other attributes of the user

If you want to check the user's email or phone number before allowing access, for example, you want to allow only emails with a specific domain to log in, you should do the check here.

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 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.

Examples

Access tokens are usually included in oauth_token.access_token in the responses from the SDK, or in the Authorization Header.

// Install Dependency
yarn add cotter-node

// Validate token
var cotterNode = require("cotter-node");
var cotterToken = require("cotter-token-js");

// Validate access token
const access_token = oauth_token.access_token;
try {
  var valid = await cotterNode.CotterValidateJWT(access_token);
} catch (e) {
  // Not Valid
  console.log(e)
}

// Read access token
let decoded = new cotterToken.CotterAccessToken(access_token);
console.log(decoded);

// Check that `aud` is your API KEY
const audience = decoded.getAudience();
if (audience !== YOUR_API_KEY_ID) {
  throw "Audience doesn't match"
}

// (Optional) Checking other attributes of the user
// Example, only allow my company domain to login
const email = decoded.getIdentifier();
if (email.split("@")[1] !== "cotter.app") {
  throw "Please use cotter business email instead of a personal email";
}

Last updated