Skip to content

Execution context + JWT token custom validations

Compare
Choose a tag to compare
@charlietfe charlietfe released this 27 Jan 13:58
· 883 commits to main since this release

This new Booster version contains a context property inside the commands Register object. In that way, the user could log, intercept or validate at the command side the content of the context object.

@Command({
  authorize: 'all',
})
export class CreatePost {
  public constructor(
    readonly postId: UUID,
    readonly title: string,
    readonly content: string,
    readonly author: string
  ) {}

  public static async handle(command: CreatePost, register: Register): Promise<void> {
    console.log('Our awesome context', register.context)
    register.events(new PostCreated(command.postId, command.title, command.content, command.author))
  }
}

Also, we support a new extraValidation function inside the TokenVerifierConfig to perform custom JWT token validations which will be executed always after the JWT standard validations, expiration, issuers checks, and so on.

This is the new signature for TokenVerifierConfig:

export type TokenVerifierConfig = {
  issuer: string
  jwksUri?: string
  publicKey?: string
  rolesClaim?: string
  extraValidation?: (jwtToken: unknown, rawToken: string) => void
}

The extraValidation function will receive the decoded token jwtToken which includes the header, payload, and signature. Also, the raw token is provided for additional checks. This extraValidation function must throw an exception if any custom validation doesn't match.

Example config:

const configWithExtraValidation = new BoosterConfig('test with extra validation')
configWithExtraValidation.tokenVerifiers = [
  {
   issuer: 'auth0',
    jwksUri: 'https://myauth0app.auth0.com/.well-known/jwks.json',
    extraValidation: (jwtToken, _rawToken) => {

     if ((jwtToken.headers as any)?.alg !== 'RS512') {
        throw 'Invalid token encoding'
      }

      if ((jwtToken.payload as any)?.['custom:role'] !== 'Admin') {
        throw 'Unauthorized'
      }
    },
  },
]