https://kotlinlang.org logo
Title
l

Louis Saglio

01/30/2019, 7:41 PM
I am trying to understand Ktor form authentication. To do so, I have created a very simple web app but I am stuck on an error for multiple hours and documentation seems incomplete or outdated.
fun Application.bank() {
    install(Authentication) {
        form("form") {
            challenge = FormAuthChallenge.Unauthorized
            passwordParamName = "password"
            userParamName = "username"
            validate { credentials ->
                println("Credentials : ${credentials.name}, ${credentials.password}")
                when {
                    credentials.name == "John" && credentials.password == "pa$$w0rd" -> UserIdPrincipal("John")
                    else -> null
                }
            }
        }
    }
    routing {
        authenticate("form") {
            route("account") {
                post {
                    call.respond(HttpStatusCode.OK, "connected")
                }
            }
        }
    }
}
To access the route /account I send this HTTP request :
POST <http://0.0.0.0:8081/account?username=Louis&password=pass>
But this raises an exception :
io.ktor.features.CannotTransformContentToTypeException: Cannot transform this request's content to class io.ktor.http.Parameters
So I guess I should not give credentials to the server via POST body. I have tried sending credentials in JSON with ContentNegocition installed but I get a similar error. If someone could help me ... I will update the documentation once I know how it works.
b

bdawg.io

01/31/2019, 3:25 AM
Providing the parameters in the URL is passing them in the Query Parameters. You can’t send them through the URL if you are expecting them in the POST request body
A raw HTTP request would look like
POST /account HTTP/1.1
Host: 0.0.0.0:8081
Content-Type: application/x-www-form-urlencoded

username=Louis&password=pass
this can be simulated in curl using
$ curl -X POST -H 'Content-Type: application/x-www-form-urlencoded' -d 'username=Louis&password=pass' <http://0.0.0.0:8081/account>
l

Louis Saglio

01/31/2019, 8:57 AM
Thanks, it works. I can't believe I lost a nearly full day on such a trivial error !😱
h

hho

01/31/2019, 9:57 AM
Also – there's a dedicated #ktor channel