我想使用会话 cookie 与 Ktor 进行身份验证,到目前为止我所拥有的是:
private const val SEVER_PORT = 8082
private const val SESSION_COOKIE_NAME = "some-cookie-name"
data class AuthSession(
val authToken: String
)
fun main() {
embeddedServer(Netty, port = SEVER_PORT, module = Application::basicAuthApplication).start(wait = true)
}
fun Application.basicAuthApplication() {
install(Sessions) {
cookie<AuthSession>(SESSION_COOKIE_NAME, SessionStorageMemory()) {
cookie.path = "/"
}
}
install(DefaultHeaders)
install(CallLogging)
install(Authentication) {
session<AuthSession> {
validate { session ->
// TODO: do the actual validation
null
}
}
}
routing {
authenticate {
get("/") {
call.respondText("Success")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但每次当我这样做时:
curl -v localhost:8082
Run Code Online (Sandbox Code Playgroud)
我得到一个 HTTP 200 和响应“成功”
我希望得到一个 HTTP 401 未授权或类似的信息。
有人可以告诉我如何使用 Ktor 进行正确的会话 cookie 身份验证吗?
谢谢
更新:
好的,我意识到有一种session身份验证类型没有在身份验证功能文档中记录。
您当前代码的问题在于您没有challenge明确指定,内部指定的默认挑战是SessionAuthChallenge.Ignore因此您必须将其更改为SessionAuthChallenge.Unauthorized或SessionAuthChallenge.Redirect
所以你的代码应该是这样的:
install(Authentication) {
session<AuthSession> {
challenge = SessionAuthChallenge.Unauthorized
validate { session ->
// TODO: do the actual validation
null
}
}
}
Run Code Online (Sandbox Code Playgroud)
老的:
您没有指定要使用的身份验证类型,可能basic,form或者jwt,您可能想尝试这样的表单身份验证,例如:
install(Authentication) {
form("login") {
skipWhen { call -> call.sessions.get<AuthSession>() != null }
userParamName = "username"
passwordParamName = "password"
challenge = FormAuthChallenge.Unauthorized
validate { credentials ->
// Handle credentials validations
}
}
}
Run Code Online (Sandbox Code Playgroud)
查看官方文档以获取更多信息。