Authenticating Clients with JWT / JWK

Ktor supports client authentication using JSON Web Tokens. The currently supported implementations are JWT and JWK. Both rely on the Auth0 implementations.


authentication {
  jwtAuthentication(...) { credential ->

Install it inside the authentication feature.


JWT and JWK each have their own method with slightly different parameters.


The JWT authentication requires a JWTVerifier instance.

val realm = ""
val jwtVerifier = JWT
jwtAuthentication(jwtVerifier, realm) { credential ->
  if (credential.payload.getClaim.contains(audience))
  else null


The JWK authentication requires a JwkProvider instance.

val realm = ""
val issuer = "https://jwk-provider-domain/"        
val jwkProvider = JwkProviderBuilder(issuer)
        .cached(10, 24, TimeUnit.HOURS)
        .rateLimited(10, 1, TimeUnit.MINUTES)

jwtAuthentication(jwkProvider, issuer, realm) { credential ->
  if (credential.payload.expiresAt.before(Date())) null
  else JWTPrincipal(credential.payload)

Both require the realm parameter, which is used in the WWW-Authenticate response header.