小编ech*_*oes的帖子

Ktor:如何检查路由处理程序内的身份验证?

我正在使用 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)

kotlin ktor

4
推荐指数
1
解决办法
5343
查看次数

标签 统计

kotlin ×1

ktor ×1