Hello, how can I retrieve a session arbitrarily? T...
# ktor
m
Hello, how can I retrieve a session arbitrarily? That is, I have sessions using a header, everything being stored on the server, the client only transmits a session ID in the header. I need to be able to retrieve the session with its ID without the header being in the call. How can I do that? In other words, how can I retrieve any session given only the session's ID?
c
Ktor’s built-in session feature has support for storing only the session ID in a cookie, which is enabled by providing a session storage (such as
directorySessionStorage
, but you can write your own storage mechanism as well). If you do not provide session storage, then the entire session contents are serialized and saved in that cookie instead. https://ktor.io/servers/features/sessions.html#directorySessionStorage You can also customize whether it expects that session ID to be in a cookie or a specified header https://ktor.io/servers/features/sessions.html#cookie-vs-header
As HTTP (and thus ktor) is stateless, you must provide either the cookie or a session header in a request, otherwise the server has no way of knowing who “you” are. However, a stateful protocol like websockets (which Ktor also supports) does allow you to maintain a persistent session without needing to repeatedly send the same session IDs with each request
m
Hi, I know all of this, the issue here is that I'm getting the ID in another way (through a
state
parameter in the URL, as I'm trying to retrieve my state upon an OIDC Provider's redirection to my server), not through the header
c
You’d probably want to find that
state
parameter from the call set it to the normal header/cookie session in the request handler, since query parameters are not persistent.
call.sessions.getOrSet
is helpful here
Copy code
get("/redirect") {
    val session: AppSession = call.sessions.getOrSet {
        val sessionId = call.parameters["state"]!!
        AppSession(sessionId)
    }
}
a
interesting topic. just to dig more, how does this work in a multi node/container setup ?
c
If the sessions are stored in a database that is shared by all nodes (as opposed to in-memory or a file which is local to each node), then it should be fairly transparent
a
ok.. i ll figure out how to configure session storage