Mic*_*rls 3 authentication jwt kotlin ktor
就上下文而言,我是 Java、Kotlin 和 Ktor 的新手(来自 C# 背景)。
我的构建收到以下错误:
Exception in thread "main" io.ktor.server.application.MissingApplicationPluginException: Application plugin Authentication is not installed
Run Code Online (Sandbox Code Playgroud)
有问题的代码部分是:
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.")
}
}
Run Code Online (Sandbox Code Playgroud)
它在以下行失败authenticate
根据文档,我已在我的build.gradle.kts文件中添加了所需的插件:
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")
}
Run Code Online (Sandbox Code Playgroud)
这是我的configureSecurity方法(取自网上的例子):
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
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在过去的九个小时里,我一直在努力解决这个问题,在网上进行了详尽的搜索,这是我最后的手段。
我正在使用从 IntelliJ IDEA 中的项目创建向导创建的 Beta 2.0 示例代码。
如何在 ktor 服务器上正确配置 JWT 身份验证?
Ale*_*man 13
问题是路由的配置在插件安装之前进行Authentication。要修复它,请交换configureRouting()并configureSecurity()调用,使其看起来像这样:
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
configureSecurity()
configureRouting()
}.start(wait = true)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3968 次 |
| 最近记录: |