6
votes

I'd like to use a session cookie for authentication with Ktor and what I have so far is:

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")
            }
        }
    }
}

But everytime when I do:

curl -v localhost:8082

I get an HTTP 200 and the response "Success"

I expected to get an HTTP 401 Not authorized or something similar.

Can somebody give me insights here how to do proper session cookie authentication with Ktor?

thanks

1

1 Answers

5
votes

UPDATE:

Okay I realized there is a session auth type which is not documented with authentication feature docs.

The issue with your current code is that you are not specifying the challenge explicitly, the default challenge specified inside is SessionAuthChallenge.Ignore so you have to change it to SessionAuthChallenge.Unauthorized or SessionAuthChallenge.Redirect

So your code should look like:

install(Authentication) {
    session<AuthSession> {
        challenge = SessionAuthChallenge.Unauthorized
        validate { session ->
            // TODO: do the actual validation
            null
        }
    }
}

OLD:

You are not specifying the type of authentication you want to use, probably basic, form or jwt, you may want to try something like this for form authentications for example:

install(Authentication) {
    form("login") {

        skipWhen { call -> call.sessions.get<AuthSession>() != null }

        userParamName = "username"
        passwordParamName = "password"
        challenge = FormAuthChallenge.Unauthorized
        validate { credentials ->
         // Handle credentials validations
       }
    }
}

Check the official documentation for more info.