您可以自定义 Ktor 401 - 未经授权的响应吗?



在 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")
}
}

最新更新