Client/Server

In Ktor, you can manage the session data in two ways:

  • Pass session data between the server and the client. In this case, you can specify how to serialize and transform the payload to sign or encrypt data sent to the client.

  • Store session data on the server and pass only a session ID between the server and the client. In such a case, you can choose where to store the payload on the server. For example, you can store session data in memory, in a specified folder, or Redis. If necessary, you can implement your own custom storage.

Client

If you pass only the session name to the cookie or header method, session data will be passed between the client and server. In this case, it is recommended to sign or encrypt data for security reasons, for example:

  1. install(Sessions) {
  2. cookie<LoginSession>("LOGIN_SESSION") {
  3. val secretSignKey = hex("000102030405060708090a0b0c0d0e0f")
  4. transform(SessionTransportTransformerMessageAuthentication(secretSignKey))
  5. }
  6. }

Invalidate Client-Side Sessions

Client-side sessions can’t be invalidated directly like server sessions. You can pass a session expiration time as a part of your session payload:

  1. data class ExpirableLoginSession(val username: String, val expiration: Long)

Then, configure a session inside the install block:

  1. install(Sessions) {
  2. cookie<ExpirableLoginSession>("EXPIRABLE_LOGIN_SESSION")
  3. }

Finally, you can get the session content and check whether the current time exceeds the specified expiration time:

  1. routing {
  2. get("/profile") {
  3. val session = call.sessions.get<ExpirableLoginSession>() ?: error("Session not found")
  4. if (System.currentTimeMillis() > session.expiration) {
  5. error("Session expired")
  6. }
  7. }
  8. }

Server

Ktor provides different storage types for storing session data on the server. For example, you can use the SessionStorageMemory in-memory storage for development purposes:

  1. install(Sessions) {
  2. cookie<LoginSession>("LOGIN_SESSION", storage = SessionStorageMemory())
  3. }

You can learn more about the available storages from Storages.