Cookie/Header Sessions

You can either use cookies or custom HTTP headers for sessions. The code is roughly the same but you have tocall either the cookie or header method, depending on where you want to send the session information.

Cookies vs Headers sessions

Depending on the consumer, you might want to transfer the sessionId or the payload using a cookie,or a header. For example, for a website, you will normally use cookies, while for an API you might want to use headers.

The Sessions.Configuration provide two methods cookie and header to select how to transfer the sessions:

Cookies

  1. application.install(Sessions) {
  2. cookie<MySession>("SESSION")
  3. }

You can configure the cookie by providing an additional block. There is a cookie property allowingto configure it, for example by adding a SameSite extension:

  1. application.install(Sessions) {
  2. cookie<MySession>("SESSION") {
  3. cookie.extensions["SameSite"] = "lax"
  4. }
  5. }

The Cookie method is intended for browser sessions. It will use a standardSet-Cookie header.Inside the cookie block, you have access to a cookie property which allows you to configure the Set-Cookie header,for example, by setting a cookie’s path or expiration, domain or https related things.

  1. install(Sessions) {
  2. cookie<SampleSession>("COOKIE_NAME") {
  3. cookie.path = "/"
  4. /* ... */
  5. }
  6. }

Headers

The Header method is intended for APIs, both for using in JavaScript XHR requests and for requesting themfrom the server side. It is usually easier for API clients to read and generate custom headers than to handlecookies.

  1. install(Sessions) {
  2. header<SampleSession>("HTTP_HEADER_NAME") { /* ... */ }
  3. }
  1. application.install(Sessions) {
  2. header<MySession>("SESSION")
  3. }

Custom storages

The Sessions API provides a SessionStorage interface, that looks like this:

  1. interface SessionStorage {
  2. suspend fun write(id: String, provider: suspend (ByteWriteChannel) -> Unit)
  3. suspend fun invalidate(id: String)
  4. suspend fun <R> read(id: String, consumer: suspend (ByteReadChannel) -> R): R
  5. }

All three functions are marked as suspend and are designed to be fully asynchronousand use ByteWriteChannel and ByteReadChannel from kotlinx.coroutines.io that provideAPIs for reading and writing from an asynchronous Channel.

In your implementations, you have to call the callbacks providing a ByteWriteChannel and a ByteReadChannelthat you have to provide: it is your responsibility to open and close them.You can read more about ByteWriteChannel and ByteReadChannel in their libraries documentation.If you just need to load or store a ByteArray, you can use this snippet which provides a simplified session storage:

SimplifiedSessionStorage.kt

  1. abstract class SimplifiedSessionStorage : SessionStorage {
  2. abstract suspend fun read(id: String): ByteArray?
  3. abstract suspend fun write(id: String, data: ByteArray?): Unit
  4. override suspend fun invalidate(id: String) {
  5. write(id, null)
  6. }
  7. override suspend fun <R> read(id: String, consumer: suspend (ByteReadChannel) -> R): R {
  8. val data = read(id) ?: throw NoSuchElementException("Session $id not found")
  9. return consumer(ByteReadChannel(data))
  10. }
  11. override suspend fun write(id: String, provider: suspend (ByteWriteChannel) -> Unit) {
  12. return provider(reader(coroutineContext, autoFlush = true) {
  13. write(id, channel.readAvailable())
  14. }.channel)
  15. }
  16. }
  17. suspend fun ByteReadChannel.readAvailable(): ByteArray {
  18. val data = ByteArrayOutputStream()
  19. val temp = ByteArray(1024)
  20. while (!isClosedForRead) {
  21. val read = readAvailable(temp)
  22. if (read <= 0) break
  23. data.write(temp, 0, read)
  24. }
  25. return data.toByteArray()
  26. }

With this simplified storage you only have to implement two simpler methods:

  1. abstract class SimplifiedSessionStorage : SessionStorage {
  2. abstract suspend fun read(id: String): ByteArray?
  3. abstract suspend fun write(id: String, data: ByteArray?): Unit
  4. }

So for example, a redis session storage would look like this:

  1. class RedisSessionStorage(val redis: Redis, val prefix: String = "session_", val ttlSeconds: Int = 3600) :
  2. SimplifiedSessionStorage() {
  3. private fun buildKey(id: String) = "$prefix$id"
  4. override suspend fun read(id: String): ByteArray? {
  5. val key = buildKey(id)
  6. return redis.get(key)?.unhex?.apply {
  7. redis.expire(key, ttlSeconds) // refresh
  8. }
  9. }
  10. override suspend fun write(id: String, data: ByteArray?) {
  11. val key = buildKey(id)
  12. if (data == null) {
  13. redis.del(buildKey(id))
  14. } else {
  15. redis.set(key, data.hex)
  16. redis.expire(key, ttlSeconds)
  17. }
  18. }
  19. }