For context, I am new to Java, Kotlin and Ktor (coming from a C# background).
I am receiving the following error from my build:
Exception in thread "main" io.ktor.server.application.MissingApplicationPluginException: Application plugin Authentication is not installed
The offending section of code is:
authenticate("auth-jwt") {
get("/hello") {
val principal = call.principal<JWTPrincipal>()
val username = principal!!.payload.getClaim("username").asString()
val expiresAt = principal.expiresAt?.time?.minus(System.currentTimeMillis())
call.respondText("Hello, $username! Token is expired at $expiresAt ms.")
}
}
It fails at the line with authenticate
Per the documentation, I have added the required plugins in my build.gradle.kts
file:
dependencies {
implementation("io.ktor:ktor-server-core-jvm:$ktor_version")
implementation("io.ktor:ktor-server-host-common-jvm:$ktor_version")
implementation("io.ktor:ktor-server-content-negotiation-jvm:$ktor_version")
implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:$ktor_version")
implementation("io.ktor:ktor-serialization-gson-jvm:$ktor_version")
implementation("io.ktor:ktor-server-netty-jvm:$ktor_version")
implementation("io.ktor:ktor-server-auth:$ktor_version")
implementation("io.ktor:ktor-server-auth-jwt:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
testImplementation("io.ktor:ktor-server-test-host:$ktor_version")
testImplementation("org.jetbrains.kotlin:kotlin-test:$kotlin_version")
}
Here is my configureSecurity
method (taken from the online examples):
fun Application.configureSecurity() {
val secret = System.getenv("JWT_SECRET")
val issuer = environment.config.property("jwt.issuer").getString()
val audience = environment.config.property("jwt.audience").getString()
val myRealm = environment.config.property("jwt.realm").getString()
authentication {
jwt("auth-jwt") {
verifier(
JWT
.require(Algorithm.HMAC256(secret))
.withAudience(audience)
.withIssuer(issuer)
.build()
)
validate { credential ->
if (credential.payload.getClaim("username").asString() != "") {
JWTPrincipal(credential.payload)
} else {
null
}
}
}
}
}
I have been working to fix this for the last nine hours, searching the web exhaustively, and this is my last resort.
I am using Beta 2.0 sample code created from the project creation wizard in IntelliJ IDEA.
How do you properly configure JWT auth on ktor server?
CodePudding user response:
The problem is that configuration for a routing goes before an installation of the Authentication
plugin. To fix it swap configureRouting()
and configureSecurity()
calls so it will look like this:
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
configureSecurity()
configureRouting()
}.start(wait = true)