您得到的不仅仅是一个空白页面,您还会得到一个 HTTP 状态代码401 (UNAUTHORIZED)
。那是因为formAuthentication
有四个参数,其中三个具有默认值。您只实现了最后一个(validate
,无默认值):
userParamName: String = "user",
passwordParamName: String = "password",
challenge: FormAuthChallenge = FormAuthChallenge.Unauthorized,
validate: (UserPasswordCredential) -> Principal?
每当你到达/login
如果没有正确的凭据,您将获得默认的路由challenge
,即FormAuthChallenge.Unauthorized
,这是一个401
回复。
而不是使用默认值challenge
,你可以使用FormAuthChallenge.Redirect
。一个需要两条路线的简短示例:
get("/login") {
val html = """
<form action="/authenticate" enctype="..."
REST OF YOUR LOGIN FORM
</form>
"""
call.respondText(html, ContentType.Text.Html)
}
route("/authenticate") {
authentication {
formAuthentication(challenge = FormAuthChallenge.Redirect({ _, _ -> "/login" })) {
credential: UserPasswordCredential ->
when {
credential.password == "secret" -> UserIdPrincipal(credential.name)
else -> null
}
}
}
handle {
val principal = call.authentication.principal<UserIdPrincipal>()
val html = "Hello, ${principal?.name}"
call.respondText(html, ContentType.Text.Html)
}
}
UPDATE
如果上述方法效果不佳,请定义userid-parameter
and password-parameter
显然,正如它们出现在form
这样做的POST
, 如下:
authentication {
formAuthentication("user", "pass",
challenge = FormAuthChallenge.Redirect({ _, _ -> "/login" })){
credential: UserPasswordCredential ->
when {
credential.password == "secret" -> UserIdPrincipal(credential.name)
else -> null
}
}
}