kotlinauthenticationserverbackendktor

Can you customize Ktor 401 - Unauthorized Response?


When implementing Basic Authentication on Ktor and configuring a Provider, which validates whether the credentials are legit by returning a non null Principal, like in this example:

install(Authentication) {
    basic("auth-basic") {
        realm = "Access to the '/' path"
        validate { credentials ->
            if (credentials.name == "fernando" && credentials.password == "foobar") {
                UserIdPrincipal(credentials.name)
            } else {
                null
            }
        }
    }
}

If the credentials are invalid and a null is returned, then Ktor automatically communicates with the client by triggering a 401 - Unauthorized, which in terms of behavior is what is expected...

But I cannot provide/add any extra information, like for example where exactly the issue was: username or password.

Any idea on how to mitigate this?


Solution

  • for resolve this problem you can use StatusPages by install it on application calss.

    like below:

    install(StatusPages) {
        status(HttpStatusCode.Unauthorized) { call, _ ->
            call.respond(HttpStatusCode.Unauthorized, "Your Response Object")
        }
    }
    

    for more informatin please read these links:
    https://ktor.io/docs/status-pages.html
    https://github.com/ktorio/ktor/issues/366