Skip to content

Add 'validate' option to allow token claim validation #316

@salmanm

Description

@salmanm

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Can we add a new validate option into the package? It should accept a function similar to the trusted option but allow us to do some custom json-schema based validations on the token payload. While the current 'trusted' option serves a similar purpose, repurposing might not be suitable given the name "trusted" which implies security and not validation.

While external validation (in the callback of request.jwtVerify) is an option, integrating 'validate' directly into @fastify/jwt aligns with JWT operations, offering more convenience and coherence. If the maintainers are on board with this proposal, I'd be more than willing to contribute by creating a Pull Request to implement the 'validate' option.

Motivation

This feature is particularly valuable in scenarios involving external Identity Providers (IDPs) where unexpected modifications to claims can disrupt the application's functionality.

Thanks

Example

fastify.register(jwt, {
  secret: 'supersecret',
  validate: (request, tokenClaims) => {
    // JSON schema-based validation logic
    if (/* condition to check token validity */) {
      return true; // Token claims are valid
    } else {
      throw new Error('Invalid token claims'); // Throw an error for invalid claims
    }
  }
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions