@fluojs/jwt
English 한국어
HTTP-agnostic JWT token core that handles signing access tokens and verifying them into a normalized JwtPrincipal.
Table of Contents
Installation
npm install @fluojs/jwt
When to Use
- When you need to issue or verify JWT access tokens in a backend application.
- When you want a stable
JwtPrincipal shape (subject, roles, scopes) regardless of the underlying token claim variants.
- When implementing refresh token rotation with replay detection.
Quick Start
Register the Module
Configure the JWT module with your signing keys and policy.
Import JWT support through JwtModule.forRoot(...) or JwtModule.forRootAsync(...).
import { Module } from '@fluojs/core';
import { JwtModule } from '@fluojs/jwt';
@Module({
imports: [
JwtModule.forRoot({
algorithms: ['HS256'],
secret: 'your-secure-secret',
issuer: 'my-api',
audience: 'my-app',
accessTokenTtlSeconds: 3600,
}),
],
})
export class AuthModule {}
Async Registration with Injected Settings
Use JwtModule.forRootAsync(...) when your JWT settings must come from another provider and still need to resolve into the standard module contract.
Async registration exports the same JWT provider surface as the synchronous path, including RefreshTokenService; resolving that service still requires refreshToken options to be configured.
import { Module, type Token } from '@fluojs/core';
import { JwtModule } from '@fluojs/jwt';
const JWT_SETTINGS = Symbol('jwt-settings');
@Module({
imports: [
JwtModule.forRootAsync({
inject: [JWT_SETTINGS],
useFactory: async (settings) => ({
accessTokenTtlSeconds: 900,
algorithms: ['HS256'],
audience: 'my-app',
issuer: settings.issuer,
secret: settings.secret,
}),
}),
],
providers: [
{
provide: JWT_SETTINGS as Token<{ issuer: string; secret: string }>,
useValue: {
issuer: 'my-api',
secret: 'your-secure-secret',
},
},
],
})
export class AuthModule {}
Sign and Verify Tokens
Inject DefaultJwtSigner to issue tokens and DefaultJwtVerifier to validate them.
import { DefaultJwtSigner, DefaultJwtVerifier } from '@fluojs/jwt';
const token = await signer.signAccessToken({
sub: 'user-123',
roles: ['admin'],
scopes: ['read:profile'],
});
const principal = await verifier.verifyAccessToken(token);
When you use JwtService.sign(payload, { expiresIn }), the per-call expiresIn override always wins over any pre-existing payload.exp value so token lifetime stays deterministic at the call site.
Common Patterns
Asymmetric Signing (RS256/ES256)
Use public/private key pairs for enhanced security across distributed systems.
const signer = new DefaultJwtSigner({
algorithms: ['RS256'],
privateKey: '...PEM...',
});
const verifier = new DefaultJwtVerifier({
algorithms: ['RS256'],
publicKey: '...PEM...',
});
Principal Normalization
@fluojs/jwt automatically unifies scope (string) and scopes (array) claims into a single scopes: string[] property in the JwtPrincipal, ensuring consistent behavior for authorization guards.
Remote JWKS verification
When verification keys come from a remote JWKS endpoint, keep the fetch path bounded so auth traffic cannot hang on a slow or stalled identity provider.
const verifier = new DefaultJwtVerifier({
algorithms: ['RS256'],
jwksRequestTimeoutMs: 5_000,
jwksUri: 'https://issuer.example.com/.well-known/jwks.json',
});
jwksRequestTimeoutMs defaults to 5_000 and aborts the outbound JWKS fetch once that budget is exceeded.
JwtService.verify(token, options) applies per-call algorithm and claim-policy overrides (issuer, audience, clockSkewSeconds, maxAge, requireExp) without rebuilding the underlying JWKS client or static key-resolution cache. Per-call verification does not replace configured key sources such as jwksUri, keys[], publicKey, secret, or secretOrKeyProvider.
Configuration Guardrails
JWT signing and verification require at least one supported algorithm in algorithms. The built-in signer supports HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, and ES512; configuration with an empty algorithm list fails fast instead of issuing or accepting ambiguous tokens.
Access-token TTL must also be a positive finite number. When accessTokenTtlSeconds is omitted, DefaultJwtSigner uses the documented 3600 second default. Fractional seconds are preserved in the JWT NumericDate exp claim; when the option is provided as 0, a negative number, or a non-finite value, signing fails with JwtConfigurationError before a token is issued.
Public API Overview
Core Classes
JwtModule: The main entry point for DI registration.
DefaultJwtSigner: Handles token issuance with default claim filling.
DefaultJwtVerifier: Handles token validation and normalization.
JwtService: A convenience facade combining signing and verification.
Types
JwtPrincipal: The normalized identity object (subject, roles, scopes, claims).
JwtVerifierOptions: Configuration for algorithms, keys, and validation policy.
Related Packages
@fluojs/passport: The auth execution layer that uses this core for guards and strategies.
@fluojs/config: Recommended for managing secrets and JWT options across environments.
Example Sources
packages/jwt/src/module.test.ts: Module registration and DI patterns.
packages/jwt/src/signing/signer.test.ts: Token signing examples.
examples/auth-jwt-passport/src/auth/auth.service.ts: Real-world token issuance.