我正在使用 ktor v0.9.2,我想根据用户是否经过身份验证,为同一路由发送不同的内容。
我遇到的问题是我无法访问块外的主体authenticate { }。
我的设置是这样的:
data class User(
val userId: Int
) : io.ktor.auth.Principal
fun Application.myApp() {
install(Authentication) {
jwt {
verifier(JwtConfig.verifier)
validate { credential ->
val userId = credential.payload.getClaim("userId").asInt()
when {
userId > 0 -> User(userId)
else -> null
}
}
}
}
install(DefaultHeaders)
install(CallLogging)
install(ContentNegotiation) {
jackson { }
}
install(Routing) {
authenticate {
get("/protected") {
// This works fine!!
val user = call.authentication.principal<User>()
call.respond(user)
}
}
get("/") {
val user = call.authentication.principal<User>() // …Run Code Online (Sandbox Code Playgroud)