Skip to content

Repository files navigation

JWT

A high-level library for working with JSON Web Tokens (JWT), making it easier to create, sign, verify, decode, and manage JWTs in your application.

Installation

Install the library along with an implementation of the @remix-run/file-storage

bun add @edgefirst-dev/jwt @remix-run/file-storage

Usage

Create a JWT

Easily create a JWT instance and access claims dynamically.

import{JWT}from"@edgefirst-dev/jwt";letjwt=newJWT(payload);jwt.issuer;// Read the issuer (iss) claimjwt.uid;// Read the uid claim

Sign a JWT

To sign a JWT, you need a signing key.

import{JWT,JWK}from"@edgefirst-dev/jwt";import{MemoryFileStorage}from"@remix-run/file-storage/memory";letstorage=newMemoryFileStorage();letjwt=newJWT(payload);lettoken=awaitjwt.sign(JWK.Algoritm.ES256,awaitJWK.signingKeys(storage));

Verify a JWT

Verify a JWT against signing keys, checking its audience and issuer

import{JWT,JWK}from"@edgefirst-dev/jwt";letjwt=awaitJWT.verify(token,awaitJWK.signingKeys(storage),{audience: "api.example.com",issuer: "idp.example.com",});

Decode a JWT

Decode a JWT without verifying its signature.

import{JWT}from"@edgefirst-dev/jwt";letjwt=JWT.decode(token);

Extend the JWT class

Customize the JWT class to add custom claims or override existing ones.

import{JWT}from"@edgefirst-dev/jwt";classCustomJWTextendsJWT{overridegetissuer(){returnthis.parser.string("iss");}getuserId(){returnthis.parser.string("uid");}}letcustomJWT=CustomJWT.decode(token);

Update a JWT instance

Modify the claims of an existing JWT instance.

import{JWT}from"@edgefirst-dev/jwt";letjwt=newJWT();jwt.issuer="new-issuer";jwt.uid="new-uid";

Verify a JWT from Locale JWKS

You can verify a JWT using a locally managed JSON Web Key Set (JWKS).

// We need to generate and import the key pairsletkeyPair=awaitJWK.importKeyPair(awaitJWK.generateKeyPair(JWK.Algoritm.ES256));letjwks=awaitJWK.importLocal({keys: [keyPair.jwk]},{alg: JWK.Algoritm.ES256});lettoken=awaitnewJWT(payload).sign(JWK.Algoritm.ES256,[keyPair]);letjwt=awaitJWT.verify(token,jwks);

Verify a JWT from Remote JWKS

Or you can fetch and use a remote JWKS to verify a JWT.

letjwks=awaitJWK.importRemote(newURL("https://example.com/.well-known/jwks.json"),{alg: JWK.Algoritm.ES256});letjwt=awaitJWT.verify(token,jwks);

Convert JWK to JSON for well-known endpoint

To expose your JWKS in a well-known endpoint.

letkeys=awaitJWK.signingKeys(storage);letresponse=Response.json(JWK.toJSON(keys));

About

A library to simplify using JWT in your application.

Resources

Contributing

Stars

18 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages

Generated from sergiodxa/package