在 Ktor 上实现基本身份验证并配置提供程序时,通过返回非空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
自动与客户端通信,这在行为方面是预期的......
但是我无法提供/添加任何额外的信息,例如问题到底在哪里:用户名或密码。
关于如何缓解这种情况的任何想法?
要解决此问题,您可以通过将其安装在应用程序calss上使用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
令牌过期时的消息可以使用 StatusPages 或使用JWTAuth
类中的challenge
方法显示,如下所示:
jwt {
challenge { _, _ ->
call.respond(HttpStatusCode.Unauthorized, "Token is not valid or has expired")
}
}