@emmert/jwt-utils

Microservice authentication tools

Usage no npm install needed!

<script type="module">
  import emmertJwtUtils from 'https://cdn.skypack.dev/@emmert/jwt-utils';
</script>

README

JWT Utils

Tools for authenticating requests with JWT tokens in a multi-service environment.

Architecture

Each service should be able to independently verify tokens without calling the auth service that issued the token, or knowing how it works. Tokens are cryptographically verified as per the JSON Web Tokens open standard.

Features

  • Verify that a token was issued with the same secret key.
  • Verify that a token isn't expired
  • Verify that a token contains all of a set of claims
  • Verify that a token contains at least one of a set of claims
  • Verify that a token was issued in the same subject (i.e. REFRESH vs AUTHENTICATION)

Installation

NPM
npm install @emmert/jwt-utils

Yarn
yarn add @emmert/jwt-utils

Configuration & Setup

This setup can be done in express middleware, GraphQL context, or the equivalent place.

Setup can be done automatically

import { createAuthContext } from "@emmert/jwt-utils";

const authContext = await createAuthContext({
    authSecret: process.env.APP_SECRET ?? "shhhhh",
});

const context = {
    ...authContext,
    ...myOtherContext,
};

or manually

import { JWTClient, extractToken, AuthSession } from "@emmert/jwt-utils";

const secret = "shhhhhh"; // Use something more secure here

const jwt = new JWTClient(secret); // Create a JWT client

...

// req in this case is a request object from express
const token = extractToken(req.headers.authorization);

// Extract the auth session from the token
const authDetails = await jwt.verify(token, {})
const session = new AuthSession(authDetails)

Authentication

Once you can access the auth session in the context of your application (express request object, GraphQL context, or equivalent), you can use any of the following features to validate the context. If a validation fails, AuthSession will throw an instance of AuthError.

Check if the token has a particular subject

session.isSubject("REFRESH");

or

session.isSubject(AuthSubject.REFRESH);

Check if the token has all of a particular set of claims

session.hasAllClaims(["TEST-1", "TEST-2"]);

Check if the token has some of a particular set of claims

session.hasSomeClaims(["TEST-3", "TEST-4"]);

Check if the token has a particular attribute (and it's any value but null/undefined)

session.hasAttribute("email");

Check if the token has a particular attribute (and it equals a particular value)

session.hasAttribute("email", "admin@admin.com");

String conditions together

session
    .hasSomeClaims(["TEST-1", "TEST-2"])
    .hasAllClaims(["TEST-3", "TEST-4"])
    .isSubject("REFRESH")
    .hasAttribute("email", "admin@admin.com");

Get attribute value

const email = session.get("email"); // jane@doe.com
const name = session.get("name"); // Jane Doe
const claims = session.get("claims"); // ["TEST-1", "TEST-2"]