Kest

Search

Search the documentation

Security

JWT and JWKS

Sign and verify JSON Web Tokens with JwtModule.forRoot or forRootAsync, create RSA keys, publish them as a JWKS, and rotate keys without breaking tokens already issued.

JwtModule signs and verifies JSON Web Tokens (RFC 7519) and protects routes with JwtAuthGuard. It supports HS256, HS384 and HS512 with a shared secret, and RS256 with an RSA key pair. For RS256 it can also create the keys and publish the public half as a JWKS (RFC 7517), so other services can verify your tokens without ever holding the secret.

Register the module

@Module(imports = [JwtModule.forRoot {
    algorithm = "RS256"
    privateKeyPem = System.getenv("JWT_PRIVATE_KEY")      // PKCS#8 PEM
    publicKeyPem = System.getenv("JWT_PUBLIC_KEY")        // X.509 PEM
    keyId = "2026-12"                                     // written into every token's header as "kid"
    issuer = "https://auth.acme.com"
    audience = "shop-api"
    expiresIn = Duration.ofHours(1)
})])
class AuthModule

Read the keys from configuration instead, with forRootAsync, so that nothing sensitive is in the code:

JwtModule.forRootAsync<ConfigService> { config ->
    algorithm = "RS256"
    privateKeyPem = config.getOrThrow("jwt.private-key")
    publicKeyPem = config.getOrThrow("jwt.public-key")
    keyId = config.getOrThrow("jwt.key-id")
}

The untyped form, JwtModule.forRootAsync { resolver -> ... }, gives you the container itself, if you need something other than configuration.

JwtModule.register and registerAsync are the same modules under the NestJS names, and they keep working.

Sign and verify

JwtService is provided by the module:

@Injectable
class SessionService(private val jwt: JwtService) {
    fun issue(user: User): String = jwt.sign(mapOf("sub" to user.id, "roles" to user.roles))
 
    fun who(token: String): Map<String, Any?> = jwt.verify(token)   // checks the signature, exp, nbf, iss and aud
}

verify refuses a token whose algorithm differs from the configured one, which blocks alg: none and key-confusion attacks. decode reads the claims without checking them; never use it for an access decision.

Protect routes

JwtAuthGuard reads Authorization: Bearer <token>, verifies it, and sets a JwtPrincipal with the sub claim as its id and the roles from the roles claim. Register it globally, and mark open routes with @Public:

@Controller("orders")
class OrdersController {
    @Get fun list(principal: JwtPrincipal): List<Order> = orders.forUser(principal.id)
 
    @Public @Get("health") fun health(): String = "ok"
}

Create RSA keys

Jwks.generateRsa makes a new key pair for RS256 and returns it as PEM, ready for the options:

val keys = Jwks.generateRsa(kid = "2026-12")          // 2048 bits by default; smaller keys are refused
println(keys.privateKeyPem)                            // keep this in a secret store
println(keys.publicKeyPem)

Generate once, store the private key in your secret store, and give the same kid to the service that signs with it. A generated key is for a new service. An existing key is loaded from its PEM text as usual.

Publish a JWKS

useJwks serves the public keys at /.well-known/jwks.json. The route is open, because public keys are not secret:

val app = Kest.run<AppModule>().http(adapter) {
    useJwks(container.get(JwtService::class))
}

The document lists the signing key and any rotated keys:

{
  "keys": [
    { "kty": "RSA", "use": "sig", "alg": "RS256", "kid": "2026-12", "n": "...", "e": "AQAB" }
  ]
}

A service that verifies your tokens finds the key by the token's kid and checks the signature. It needs no secret. Standard JWT libraries read this format.

JwtService.jwks() returns the same document as a map, if you want to serve it somewhere else.

Rotate keys

A rotation has three steps, and no token is rejected in between:

  1. Generate the new key with a new kid, for example 2027-01.
  2. Keep the old public key, and add it with publicKey(...). Start the service with the new signing key:
JwtModule.forRoot {
    algorithm = "RS256"
    privateKeyPem = newKeys.privateKeyPem
    publicKeyPem = newKeys.publicKeyPem
    keyId = "2027-01"
    publicKey("2026-12", oldKeys.publicKeyPem)     // tokens signed with the old key still verify
}
  1. Once every token signed with the old key has expired, remove the publicKey(...) line. The JWKS then lists only the new key.

Verification picks the key named by each token's kid, so the old tokens and the new tokens are checked against the right keys at the same time.

Options

OptionUse
algorithmHS256, HS384, HS512 or RS256.
secretThe shared secret for the HS algorithms.
privateKeyPem, publicKeyPemThe RSA keys for RS256.
keyIdThe kid written into the header. Needed for a JWKS.
publicKey(kid, pem)An extra public key, for rotation.
expiresInHow long a signed token lives. It sets exp, and sign(claims, expiresIn) can change it for one token.
issuer, audienceWritten into signed tokens, and checked when verifying.
clockToleranceSecondsForgives a small clock difference between services.
rolesClaimThe claim that holds the roles. Defaults to roles.