【问题标题】:Ktor prompt for credentials from within route interceptor inside a basic authentication blockKtor 提示来自基本身份验证块内的路由拦截器内的凭据
【发布时间】:2019-09-11 03:52:13
【问题描述】:

当我设置一个基本的身份验证提供程序并将一个简单的get 处理程序放在authenticate 块中时,当我尝试访问路由时会提示我输入凭据,因此一旦开始执行 get 处理程序,我可以访问UserIdPrincipal 并开始查找与该帐户关联的数据。但是,我现在想扩展我的authenticate 块以包含多个路由,所以我认为我可以在intercept 块内处理主体/帐户的初始处理。然而,当我尝试执行此操作时,系统不会提示我输入凭据,因此拦截器内的 UserIdPrincipal 为空。如何让 Ktor 在 authenticate 块内的路由拦截器中提示我输入凭据?

当我尝试访问仪表板路由时,此代码会正确提示我输入凭据。

authenticate("teacherAuth") {
    get("dashboard") {
        val principal = call.principal<UserIdPrincipal>()!!
        val schoolName = principal.name
        val school = transaction {
            School.find { Schools.name eq schoolName }.singleOrNull()
        }
        if (school == null)
            call.respondText("No school \"$schoolName\" found")
        else
            call.respondHtml {
                ...
            }
    }
}

当我尝试访问仪表板路由时,此代码不会提示我输入凭据,从而导致错误。

authenticate("teacherAuth") {
    val schoolKey = AttributeKey<School>("school")

    intercept(ApplicationCallPipeline.Setup) {
        val principal = call.principal<UserIdPrincipal>()!!
        val schoolName = principal.name
        val school = transaction {
            School.find { Schools.name eq schoolName }.singleOrNull()
        }
        if (school == null) {
            call.respondText("No school \"$schoolName\" found")
            return@intercept finish()
        }
        call.attributes.put(schoolKey, school)
    }

    get("dashboard") {
        val school = call.attributes[schoolKey]
        call.respondHtml {
            ...
        }
    }
}

【问题讨论】:

  • 可能是你在错误的阶段拦截。身份验证通常在功能阶段。您在验证之前的设置阶段进行拦截。
  • 谢谢,将拦截器阶段设置为ApplicationCallPipeline.Call 解决了这个问题。

标签: kotlin basic-authentication ktor


【解决方案1】:

将拦截器阶段设置为ApplicationCallPipeline.Call 解决了问题,现在提示我输入凭据。感谢 @f-caron 的想法。

【讨论】:

    猜你喜欢
    • 2019-10-29
    • 2017-11-11
    • 2015-03-24
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    相关资源
    最近更新 更多