@byu-oit-sdk/jwt
v0.4.0
Published
JSON Web Token validation for the BYU OIT SDK
Readme
@byu-oit-sdk/jwt
Requirements:
- Node.js 18+
- npm v9+
Installing
In addition to installing this module, you can install either the Jwt plugin for Fastify or for Express depending on what you're using.
npm install @byu-oit-sdk/jwtIntroduction
Use this module for verification and decoding of JWTs. Can be used in conjunction with the express and fastify plugins.
The current implementation uses jose internally for JWT verification and JWK handling.
This package exports the following:
Jwk- A class for verifying Jwks.RsaJwk- A class for verifying RSA JWKs. Extension of theJwkclass.JwkSet- A class which handles construction, validation, and loading of Jwk Sets.createJwt()- A function that returns a class with methods for verifying and decoding JWTs.
Options
The following options can be passed in to the CreateJwt() function.
| Option | Type | Default | Description | |-----------------------|--------------------|-----------------|--------------------------------------------------------------------------------------------------------------------| | Schema | Object | REQUIRED OPTION | The schema of the payload of the JWT that you are creating. | | transformer | function | - | The function that you will use for manipulating the JWT you are authenticating. | | additionalValidations | array of functions | - | An optional array of functions that will also be used to validate the JWT. | | key | string | REQUIRED OPTION | This is required but can be an empty string. | | discoveryEndpoint | string | - | The redirection endpoint that the authorization server should redirect to after authenticating the resource owner. | | issuer | string | - | Used to configure where the user will be sent to sign in. |
Usage
import { createJwt, Jwt, type JwtData } from '../src/Jwt.js'
import { type Static, Type } from '@sinclair/typebox'
const sampleJwtData = {
header: {
alg: 'HS256',
typ: 'JWT'
},
payload: {
id: 'some id',
name: 'some Name'
},
signature: 'some signature'
}
const UserSchema = Type.Object({
id: Type.String(),
name: Type.String()
})
const TransformedJwtPayload = Type.Object({
userId: Type.String(),
userName: Type.String()
})
const jwtData: JwtData<Static<typeof UserSchema>> = {
header: { alg: 'HS256', typ: 'JWT', kid: 'testKid' },
payload: { id: '1', name: 'Alice' },
signature: 'sample_signature'
}
const payloadTransformer = (payload: typeof UserSchema): Static<typeof TransformedJwtPayload> => {
const userId = payload.id
const userName = payload.name
return {
userId,
userName
}
}
const instance = new Jwt(jwtData, { transformer: payloadTransformer })
const CustomJwt = createJwt({
schema: UserSchema,
key: ''
})
