问题
I'm new to Kotlin
and Ktor
trying to see the authentication part, so I got the below code.
Routes "/" and "/bye" are working fine, but route "login" given blank page!
package blog
import kotlinx.html.*
import kotlinx.html.stream.* // for createHTML
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.auth.*
import org.jetbrains.ktor.features.*
import org.jetbrains.ktor.http.*
import org.jetbrains.ktor.response.*
import org.jetbrains.ktor.routing.*
import org.jetbrains.ktor.request.* // for request.uri
import org.jetbrains.ktor.html.*
import org.jetbrains.ktor.pipeline.*
import org.jetbrains.ktor.host.* // for embededServer
import org.jetbrains.ktor.netty.* // for Netty
fun main(args: Array<String>) {
embeddedServer(Netty, 8080, watchPaths = listOf("BlogAppKt"), module = Application::module).start()
}
fun Application.module() {
install(DefaultHeaders)
install(CallLogging)
intercept(ApplicationCallPipeline.Call) {
if (call.request.uri == "/hi")
call.respondText("Test String")
}
install(Routing) {
get("/") {
call.respondText("""Hello, world!<br><a href="/bye">Say bye?</a>""", ContentType.Text.Html)
}
get("/bye") {
call.respondText("""Good bye! <br><a href="/login">Login?</a> """, ContentType.Text.Html)
}
route("/login") {
authentication {
formAuthentication { up: UserPasswordCredential ->
when {
up.password == "ppp" -> UserIdPrincipal(up.name)
else -> null
}
}
}
handle {
val principal = call.authentication.principal<UserIdPrincipal>()
if (principal != null) {
call.respondText("Hello, ${principal.name}")
} else {
val html = createHTML().html {
body {
form(action = "/login", encType = FormEncType.applicationXWwwFormUrlEncoded, method = FormMethod.post) {
p {
+"user:"
textInput(name = "user") {
value = principal?.name ?: ""
}
}
p {
+"password:"
passwordInput(name = "pass")
}
p {
submitInput() { value = "Login" }
}
}
}
}
call.respondText(html, ContentType.Text.Html)
}
}
}
}
}
When I disabled the authentication part below, the route '/login' displayed the required form, which means the error is most likely in this part or in the way of calling it? I guess.
authentication {
formAuthentication { up: UserPasswordCredential ->
when {
up.password == "ppp" -> UserIdPrincipal(up.name)
else -> null
}
}
}
回答1:
You're not simply given a blank page, you get a HTTP status code of 401 (UNAUTHORIZED)
. That's because formAuthentication
has four parameters, three of them with defaults. You only implemented the last one (validate
, without default):
userParamName: String = "user",
passwordParamName: String = "password",
challenge: FormAuthChallenge = FormAuthChallenge.Unauthorized,
validate: (UserPasswordCredential) -> Principal?
Whenever you reach the /login
route without the right credentials already in place, you get the default for challenge
, which is FormAuthChallenge.Unauthorized
, which is a 401
response.
Instead of using the default for challenge
, you could use a FormAuthChallenge.Redirect
. A short example that requires two routes:
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
In case the above did not work well, define both the userid-parameter
and password-parameter
clearly as they appear in the form
that do the POST
, as below:
authentication {
formAuthentication("user", "pass",
challenge = FormAuthChallenge.Redirect({ _, _ -> "/login" })){
credential: UserPasswordCredential ->
when {
credential.password == "secret" -> UserIdPrincipal(credential.name)
else -> null
}
}
}
来源:https://stackoverflow.com/questions/46500030/form-authentication-in-ktor