JWT (JSON Web Token) authentication plugin for Ktor server applications
npx @tessl/cli install tessl/maven-io-ktor--ktor-server-auth-jwt-jvm@3.2.0Ktor JWT Authentication provides JWT (JSON Web Token) authentication functionality for Ktor server applications. It offers a comprehensive authentication plugin that supports JWT token verification using various algorithms, integrates with JWK (JSON Web Key) providers for dynamic key resolution, and provides convenient access to JWT claims through a type-safe API.
implementation("io.ktor:ktor-server-auth-jwt-jvm:3.2.0")import io.ktor.server.auth.jwt.*
import io.ktor.server.auth.*
import io.ktor.server.application.*import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
fun Application.configureSecurity() {
install(Authentication) {
jwt("auth-jwt") {
realm = "ktor sample app"
verifier(
JWT
.require(Algorithm.HMAC256("secret"))
.withAudience("jwt-audience")
.withIssuer("jwt-issuer")
.build()
)
validate { credential ->
if (credential.payload.audience.contains("jwt-audience")) {
JWTPrincipal(credential.payload)
} else {
null
}
}
}
}
}The JWT authentication plugin integrates with Ktor's authentication pipeline through several key components:
JWTAuthenticationProvider handles the authentication flowJWTCredential and JWTPrincipal provide type-safe access to JWT claimsjwt function and Config classConfigure JWT authentication with verifiers, validation, and challenge handling.
/**
* Installs the JWT Authentication provider
*/
fun AuthenticationConfig.jwt(
name: String? = null,
configure: JWTAuthenticationProvider.Config.() -> Unit
)Base class providing convenient access to standard JWT claims and custom claims.
/**
* Base class for JWT credential and principal with shortcut functions for standard JWT claims
*/
abstract class JWTPayloadHolder(
val payload: Payload
) {
/** Gets the 'iss' (issuer) claim */
val issuer: String?
/** Gets the 'sub' (subject) claim */
val subject: String?
/** Gets the 'aud' (audience) claim as a list */
val audience: List<String>
/** Gets the 'exp' (expiration time) claim */
val expiresAt: Date?
/** Gets the 'nbf' (not before time) claim */
val notBefore: Date?
/** Gets the 'iat' (issued at) claim */
val issuedAt: Date?
/** Gets the 'jti' (JWT ID) claim */
val jwtId: String?
/**
* Gets a non-RFC JWT claim by name as a string
* @param name claim key as it appears in the JSON object
* @return claim value or null if not available or not a string
*/
operator fun get(name: String): String?
/**
* Gets a non-RFC JWT claim by name as the specified type
* @param name claim key as it appears in the JSON object
* @param clazz Kotlin class to deserialize the claim to
* @return claim value or null if not available or unable to deserialize
*/
fun <T : Any> getClaim(name: String, clazz: KClass<T>): T?
/**
* Gets a non-RFC JWT claim by name as a list of the specified type
* @param name claim key as it appears in the JSON object
* @param clazz Kotlin class for list elements
* @return claim value as list or empty list if not available or unable to deserialize
*/
fun <T : Any> getListClaim(name: String, clazz: KClass<T>): List<T>
}Classes representing JWT credentials and authenticated principals.
/**
* JWT credential that consists of the specified payload
* @param payload JWT payload
*/
class JWTCredential(payload: Payload) : JWTPayloadHolder(payload)
/**
* JWT principal that consists of the specified payload
* @param payload JWT payload
*/
class JWTPrincipal(payload: Payload) : JWTPayloadHolder(payload)Configuration options for JWT authentication including verifiers, validation, and challenge handling.
class JWTAuthenticationProvider.Config {
/** JWT realm to be passed in WWW-Authenticate header */
var realm: String
/**
* Configure how to retrieve HTTP authentication header
* @param block function that extracts auth header from ApplicationCall
*/
fun authHeader(block: (ApplicationCall) -> HttpAuthHeader?)
/**
* Configure authentication schemes
* @param defaultScheme default scheme used to challenge the client
* @param additionalSchemes additional schemes accepted during validation
*/
fun authSchemes(defaultScheme: String = "Bearer", vararg additionalSchemes: String)
/**
* Set JWT verifier instance
* @param verifier verifies token format and signature
*/
fun verifier(verifier: JWTVerifier)
/**
* Set JWT verifier function
* @param verifier function that returns verifier based on auth header
*/
fun verifier(verifier: (HttpAuthHeader) -> JWTVerifier?)
/**
* Set verifier with JWK provider and issuer
* @param jwkProvider provides the JSON Web Key
* @param issuer the issuer of the JSON Web Token
* @param configure function applied during JWTVerifier construction
*/
fun verifier(jwkProvider: JwkProvider, issuer: String, configure: JWTConfigureFunction = {})
/**
* Set verifier with JWK provider only
* @param jwkProvider provides the JSON Web Key
* @param configure function applied during JWTVerifier construction
*/
fun verifier(jwkProvider: JwkProvider, configure: JWTConfigureFunction = {})
/**
* Set verifier with issuer, audience and algorithm
* @param issuer of the JSON Web Token
* @param audience restriction
* @param algorithm for validation of token signatures
* @param block additional verification configuration
*/
fun verifier(
issuer: String,
audience: String,
algorithm: Algorithm,
block: Verification.() -> Unit = {}
)
/**
* Set verifier with issuer (creates JWK provider automatically)
* @param issuer the issuer of JSON Web Token
* @param block configuration of JwkProvider
*/
fun verifier(issuer: String, block: JWTConfigureFunction = {})
/**
* Set validation function for additional JWT payload validation
* @param validate function that validates JWT credential and returns principal or null
*/
fun validate(validate: suspend ApplicationCall.(JWTCredential) -> Any?)
/**
* Set challenge function for authentication failures
* @param block function that handles authentication challenges
*/
fun challenge(block: JWTAuthChallengeFunction)
}Context and function types for handling authentication challenges.
/**
* Context for JWT authentication challenge
* @param call the current application call
*/
class JWTChallengeContext(
val call: ApplicationCall
)
/**
* Function type for JWT authentication challenge
*/
typealias JWTAuthChallengeFunction =
suspend JWTChallengeContext.(defaultScheme: String, realm: String) -> Unit
/**
* Function type for JWT verifier configuration
*/
typealias JWTConfigureFunction = Verification.() -> UnitThe JWT authentication plugin relies on these external types from the auth0 library:
// From com.auth0.jwt.interfaces
interface Payload {
val issuer: String?
val subject: String?
val audience: List<String>?
val expiresAt: Date?
val notBefore: Date?
val issuedAt: Date?
val id: String?
fun getClaim(name: String): Claim
}
interface JWTVerifier {
fun verify(token: String): DecodedJWT
}
// From com.auth0.jwt.algorithms
class Algorithm
// From com.auth0.jwt
class Verification {
fun build(): JWTVerifier
}
// From com.auth0.jwk
interface JwkProvider {
fun get(keyId: String): Jwk
}// From io.ktor.server.application
interface ApplicationCall
// From io.ktor.http.auth
sealed class HttpAuthHeader {
class Single(val authScheme: String, val blob: String) : HttpAuthHeader()
class Parameterized(val authScheme: String, val parameters: List<HeaderValueParam>) : HttpAuthHeader()
}
// From io.ktor.server.auth
interface AuthenticationContext
class AuthenticationProvider
class AuthenticationProvider.Config
interface AuthenticationConfig