@dismissible/nestjs-jwt-auth-hook
v3.0.0
Published
JWT authentication hook for Dismissible applications using OIDC well-known discovery
Maintainers
Readme
Dismissible manages the state of your UI elements across sessions, so your users see what matters, once! No more onboarding messages reappearing on every tab, no more notifications haunting users across devices. Dismissible syncs dismissal state everywhere, so every message is intentional, never repetitive.
@dismissible/nestjs-jwt-auth-hook
JWT authentication hook for Dismissible applications using OpenID Connect (OIDC) well-known discovery.
Overview
This library provides a lifecycle hook that integrates with the @dismissible/nestjs-core module to authenticate requests using JWT bearer tokens. It validates tokens using JWKS (JSON Web Key Set) fetched from an OIDC well-known endpoint.
Installation
npm install @dismissible/nestjs-jwt-auth-hook @nestjs/axios axiosUsage
Basic Setup
import { Module } from '@nestjs/common';
import { DismissibleModule } from '@dismissible/nestjs-core';
import { JwtAuthHookModule, JwtAuthHook } from '@dismissible/nestjs-jwt-auth-hook';
@Module({
imports: [
// Configure the JWT auth hook module
JwtAuthHookModule.forRoot({
wellKnownUrl: 'https://auth.example.com/.well-known/openid-configuration',
issuer: 'https://auth.example.com',
audience: 'my-api',
}),
// Pass the hook to the DismissibleModule
DismissibleModule.forRoot({
hooks: [JwtAuthHook],
// ... other options
}),
],
})
export class AppModule {}Async Configuration
When configuration values come from environment variables or other async sources:
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { DismissibleModule } from '@dismissible/nestjs-core';
import { JwtAuthHookModule, JwtAuthHook } from '@dismissible/nestjs-jwt-auth-hook';
@Module({
imports: [
JwtAuthHookModule.forRootAsync({
useFactory: (configService: ConfigService) => ({
wellKnownUrl: configService.getOrThrow('OIDC_WELL_KNOWN_URL'),
issuer: configService.get('OIDC_ISSUER'),
audience: configService.get('OIDC_AUDIENCE'),
}),
inject: [ConfigService],
}),
DismissibleModule.forRoot({
hooks: [JwtAuthHook],
}),
],
})
export class AppModule {}Configuration Options
| Option | Type | Required | Default | Description |
| ------------------- | ---------- | -------- | ----------- | ------------------------------------------------------------------------------------------- |
| enabled | boolean | Yes | true | Whether JWT authentication is enabled |
| wellKnownUrl | string | Yes* | - | The OIDC well-known URL (e.g., https://auth.example.com/.well-known/openid-configuration) |
| issuer | string | No | - | Expected issuer (iss) claim. If not provided, issuer validation is skipped. |
| audience | string | No | - | Expected audience (aud) claim. If not provided, audience validation is skipped. |
| algorithms | string[] | No | ['RS256'] | Allowed algorithms for JWT verification |
| jwksCacheDuration | number | No | 600000 | JWKS cache duration in milliseconds (10 minutes) |
| requestTimeout | number | No | 30000 | Request timeout in milliseconds (30 seconds) |
| priority | number | No | -100 | Hook priority (lower numbers run first) |
| matchUserId | boolean | No | true | Enable user ID matching against JWT claim |
| userIdClaim | string | No | 'sub' | The JWT claim key to use for user ID matching |
| userIdMatchType | string | No | 'exact' | Match method: exact, substring, or regex |
| userIdMatchRegex | string | No** | - | Regex pattern for user ID matching (required when type is regex) |
* wellKnownUrl is only required when enabled is true.
** userIdMatchRegex is required when userIdMatchType is regex.
User ID Match Types
The userIdMatchType option controls how the user ID from the JWT token claim is compared to the userId in the request URL path:
exact(default): The token claim value must exactly match the URL user ID.substring: The URL user ID must be contained within the token claim value.regex: The regex pattern is applied to the token claim value. If a capture group is present, the first capture group is extracted and compared to the URL user ID. If no capture group is present, the full match is used.
Regex Matching Examples
For a token with sub claim value FfXHGud25MDOUGjQyBZnCWkkWlFDCS0Y@clients:
| Pattern | Extracted Value | URL userId | Result |
| ----------------- | ---------------------------------- | ---------------------------------- | -------- |
| ^(.+)@clients$ | FfXHGud25MDOUGjQyBZnCWkkWlFDCS0Y | FfXHGud25MDOUGjQyBZnCWkkWlFDCS0Y | Match |
| ^(\w+)@clients$ | FfXHGud25MDOUGjQyBZnCWkkWlFDCS0Y | FfXHGud25MDOUGjQyBZnCWkkWlFDCS0Y | Match |
| clients$ | clients | clients | Match |
| @clients$ | @clients | FfXHGud25MDOUGjQyBZnCWkkWlFDCS0Y | No Match |
Tip: Use capture groups to extract the meaningful part of the token claim value for comparison with the URL user ID.
Environment Variables
When using the Dismissible API Docker image or the standalone API, these environment variables configure JWT authentication:
| Variable | Description | Default |
| ------------------------------------------ | -------------------------------------- | -------- |
| DISMISSIBLE_JWT_AUTH_ENABLED | Enable JWT authentication | true |
| DISMISSIBLE_JWT_AUTH_WELL_KNOWN_URL | OIDC well-known URL for JWKS discovery | "" |
| DISMISSIBLE_JWT_AUTH_ISSUER | Expected issuer claim (optional) | "" |
| DISMISSIBLE_JWT_AUTH_AUDIENCE | Expected audience claim (optional) | "" |
| DISMISSIBLE_JWT_AUTH_ALGORITHMS | Allowed algorithms (comma-separated) | RS256 |
| DISMISSIBLE_JWT_AUTH_JWKS_CACHE_DURATION | JWKS cache duration in ms | 600000 |
| DISMISSIBLE_JWT_AUTH_REQUEST_TIMEOUT | Request timeout in ms | 30000 |
| DISMISSIBLE_JWT_AUTH_PRIORITY | Hook priority (lower runs first) | -100 |
| DISMISSIBLE_JWT_AUTH_MATCH_USER_ID | Enable user ID matching | true |
| DISMISSIBLE_JWT_AUTH_USER_ID_CLAIM | JWT claim key for user ID matching | sub |
| DISMISSIBLE_JWT_AUTH_USER_ID_MATCH_TYPE | User ID match method | exact |
| DISMISSIBLE_JWT_AUTH_USER_ID_MATCH_REGEX | Regex pattern for user ID matching | "" |
Example: Disabling JWT Auth for Development
docker run -p 3001:3001 \
-e DISMISSIBLE_JWT_AUTH_ENABLED=false \
-e DISMISSIBLE_STORAGE_POSTGRES_CONNECTION_STRING="postgresql://..." \
dismissibleio/dismissible-api:latestExample: Enabling JWT Auth with Auth0
docker run -p 3001:3001 \
-e DISMISSIBLE_JWT_AUTH_ENABLED=true \
-e DISMISSIBLE_JWT_AUTH_WELL_KNOWN_URL="https://your-tenant.auth0.com/.well-known/openid-configuration" \
-e DISMISSIBLE_JWT_AUTH_ISSUER="https://your-tenant.auth0.com/" \
-e DISMISSIBLE_JWT_AUTH_AUDIENCE="your-api-identifier" \
-e DISMISSIBLE_STORAGE_POSTGRES_CONNECTION_STRING="postgresql://..." \
dismissibleio/dismissible-api:latestHow It Works
Initialization: On module initialization, the hook fetches the OIDC configuration from the well-known URL to discover the JWKS endpoint.
Token Extraction: For each request, the hook extracts the bearer token from the
Authorizationheader.Token Validation: The token is validated by:
- Decoding the JWT to get the key ID (
kid) - Fetching the corresponding public key from JWKS
- Verifying the signature
- Validating claims (expiration, issuer, audience)
- Decoding the JWT to get the key ID (
Request Handling:
- If valid: The request proceeds
- If invalid: The request is blocked with a
403 Forbiddenresponse
Error Responses
When authentication fails, the hook returns a structured error:
{
"statusCode": 403,
"message": "Authorization failed: Token expired",
"error": "Forbidden"
}Common error messages:
Authorization required: Missing or invalid bearer tokenAuthorization failed: Token expiredAuthorization failed: Invalid signatureAuthorization failed: Unable to find signing key
Supported OIDC Providers
This hook works with any OIDC-compliant identity provider, including:
- Auth0
- Okta
- Keycloak
- Azure AD
- Google Identity Platform
- AWS Cognito
License
MIT
