【问题标题】:Can you customize Ktor 401 - Unauthorized Response?您可以自定义 Ktor 401 - 未经授权的响应吗?
【发布时间】:2021-09-03 13:28:16
【问题描述】:

在 Ktor 上实现 Basic Authentication 并配置 Provider 时,通过返回非 null 来验证 凭据是否合法 Principal,如下例所示:

install(Authentication) {
    basic("auth-basic") {
        realm = "Access to the '/' path"
        validate { credentials ->
            if (credentials.name == "fernando" && credentials.password == "foobar") {
                UserIdPrincipal(credentials.name)
            } else {
                null
            }
        }
    }
}

如果凭据无效并返回 null,则 Ktor 通过触发 401 - Unauthorized 自动与客户端通信,这在行为方面是预期的......

但我无法提供/添加任何额外信息,例如问题出在哪里:用户名或密码。

关于如何减轻这种情况的任何想法?

【问题讨论】:

标签: kotlin authentication server backend ktor


【解决方案1】:

要解决此问题,您可以通过将其安装在应用程序类上来使用 StatusPages。

如下:

install(StatusPages) {
    status(HttpStatusCode.Unauthorized) {
        call.respond(HttpStatusCode.Unauthorized, "Your Response Object")
    }
}

更多信息请阅读以下链接:
https://ktor.io/docs/status-pages.html
https://github.com/ktorio/ktor/issues/366

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-07
    • 2019-01-16
    • 2017-03-20
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多