Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Authentication

Sessions and Cookies

Use the Ktor Sessions plugin: cookie-based client sessions, signing and encryption, server-side session storage, session authentication, cookie flags and logout.

A session lets the server recognise a returning browser across requests. The usual mechanism is a cookie: the server sets it in a response, and the browser sends it back automatically with every later request to that site. For server-rendered sites and browser-based apps, sessions are simpler and safer than hand-managed tokens. This lesson covers Ktor's Sessions plugin, the two places session data can live, the cookie flags that matter for security, and a login/logout flow.

Cookies in two minutes

A server sets a cookie with a header: Set-Cookie: user_session=abc123; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Lax. The browser stores it and returns Cookie: user_session=abc123 with every request to that site until it expires. The important attributes:

Attribute Effect
HttpOnly JavaScript cannot read the cookie, which blunts XSS token theft
Secure Sent only over HTTPS
SameSite=Lax / Strict Not sent on most cross-site requests, which blunts CSRF
Path, Domain Which URLs receive the cookie
Max-Age / Expires Lifetime; omit for a browser-session cookie

The Sessions plugin

Dependency: ktor-server-sessions. You describe the session data as a class, and choose how it is carried:

Kotlin
import io.ktor.server.sessions.*

@Serializable
data class UserSession(val username: String, val loginAt: Long)

fun Application.module() {
    val secretSignKey = hex(environment.config.property("session.signKey").getString())

    install(Sessions) {
        cookie<UserSession>("user_session") {
            cookie.path = "/"
            cookie.maxAgeInSeconds = 3600
            cookie.httpOnly = true
            cookie.secure = true
            cookie.extensions["SameSite"] = "Lax"
            transform(SessionTransportTransformerMessageAuthentication(secretSignKey))
        }
    }

    routing {
        post("/login") {
            val form = call.receiveParameters()
            val user = userService.verify(form["username"].orEmpty(), form["password"].orEmpty())
            if (user == null) return@post call.respond(HttpStatusCode.Unauthorized, "Invalid credentials")
            call.sessions.set(UserSession(user.name, System.currentTimeMillis()))
            call.respondRedirect("/dashboard")
        }
        get("/dashboard") {
            val session = call.sessions.get<UserSession>()
                ?: return@get call.respondRedirect("/login")
            call.respondText("Welcome back, ${session.username}")
        }
        post("/logout") {
            call.sessions.clear<UserSession>()
            call.respondRedirect("/")
        }
    }
}

sessions.set writes the cookie, sessions.get<T>() reads it (or null), and sessions.clear<T>() deletes it.

Where does the data live?

  1. Client-side session (cookie<T>("name"), as above). The whole UserSession is serialised into the cookie. The server stores nothing. The cookie is protected with transform(...): SessionTransportTransformerMessageAuthentication adds an HMAC so any tampering is detected, and SessionTransportTransformerEncrypt also encrypts the content. Without a transformer the user could edit their own session, so always sign. Keep the data small (cookies are limited to about 4 KB).
  2. Server-side session (cookie<T>("name", storage)). The cookie contains only a random session ID; the data lives in a SessionStorage: in memory (SessionStorageMemory, for development), a directory (directorySessionStorage), or your own implementation backed by Redis or a database. This is better for large data and gives you instant revocation: delete the entry and the session is dead.
Kotlin
install(Sessions) {
    cookie<UserSession>("user_session", SessionStorageMemory()) {
        cookie.path = "/"
        cookie.maxAgeInSeconds = 3600
    }
}

Choose client-side sessions for small, low-risk data; server-side sessions when you need revocation, large data or stronger secrecy.

Using sessions for authentication

The session authentication provider connects the plugin to authenticate { }:

Kotlin
install(Authentication) {
    session<UserSession>("auth-session") {
        validate { session ->
            if (userService.exists(session.username)) session else null   // check the user still exists
        }
        challenge {
            call.respondRedirect("/login")       // browsers get redirected, not a bare 401
        }
    }
}

routing {
    authenticate("auth-session") {
        get("/dashboard") {
            val session = call.principal<UserSession>()!!
            call.respondText("Welcome ${session.username}")
        }
    }
}
  • Sign (or encrypt) client-side sessions with a long random key from configuration, not from code.
  • Set HttpOnly, Secure (production) and SameSite=Lax or Strict.
  • Regenerate the session on login (a new ID or cookie value), to avoid session fixation.
  • Give sessions an expiry; consider idle timeouts too.
  • For state-changing requests from browsers (forms), add CSRF protection: SameSite helps, and for APIs used with cookie auth consider a CSRF token or custom header check.
  • Clear the session on logout, and on the server for server-side storage.

This program implements both ideas with real HMAC. First, a client-side session: the cookie carries base64(data).signature, and tampering is caught. Second, a server-side session: the cookie carries a random ID and the data stays in a map, so "logout" simply removes the entry. Random IDs are seeded for deterministic output.

Kotlin Stand-in: signed cookie vs server-side session

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Note the trade-off visible in the output: the signed cookie can be read by the user (signing is not encryption) but cannot be changed; the server-side session keeps data private and can be revoked, at the cost of storage and a lookup.

Sessions or JWT?

Cookie sessions JWT in Authorization
Best for Browser apps on your own domain Mobile apps, SPAs on other origins, service-to-service
Revocation Easy with server-side storage Hard; short expiry plus refresh tokens
CSRF Must be considered Not an issue for header tokens
XSS Safe with HttpOnly Risky if stored in localStorage

They can coexist: configure both providers and accept either with authenticate("auth-session", "auth-jwt").

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the HttpOnly cookie flag do?

    HttpOnly hides the cookie from document.cookie, which limits damage from XSS.
  2. 2. Why must a client-side session cookie be signed or encrypted?

    The session data lives in a cookie the user controls, so it must be tamper-evident.
  3. 3. Which storage style allows you to invalidate a session instantly on the server?

    Deleting the server-side entry kills the session; a signed client cookie stays valid until it expires.
  4. 4. What is session fixation, and what prevents it?

    Issuing a fresh session at login makes a pre-planted ID useless.

Summary

  • Sessions use cookies; install Sessions, then sessions.set, get and clear.
  • Client-side sessions put signed data in the cookie; server-side sessions put an ID in the cookie and data in storage.
  • Always sign or encrypt client-side data; set HttpOnly, Secure, SameSite; regenerate on login; expire sessions.
  • The session authentication provider plugs sessions into authenticate { }.

Next: OAuth and Authorization