---
title: Set SameSite On Session Cookies
impact: MEDIUM
impactDescription: provides fundamental Cross-Site Request Forgery (CSRF) protection
tags: cookies, samesite, csrf, session, security, kotlin
---

## Set SameSite On Session Cookies

The `SameSite` attribute tells the browser whether to send cookies in cross-site requests. Setting this to `Strict` or `Lax` provides a strong baseline defense against CSRF attacks.

**Incorrect (no SameSite attribute):**

```kotlin
// Ktor
call.response.cookies.append("session", token) // SameSite not specified

// Servlet / Spring Boot (Old versions or manual Cookie setting)
val cookie = Cookie("session", token)
response.addCookie(cookie) // No native SameSite setter in standard Servlet API < 6.0
```

**Correct (SameSite set):**

```kotlin
// Ktor
import io.ktor.http.*
call.response.cookies.append(
    name = "session",
    value = token,
    httpOnly = true,
    secure = true,
    extensions = mapOf("SameSite" to "Strict") // or "Lax"
)

// Spring Boot / Spring Security (Recommended approach)
// Configure in application.properties/yml
// server.servlet.session.cookie.same-site=strict

// Manual Header (if using raw Response and older Servlet API)
response.setHeader("Set-Cookie", "session=$token; Path=/; HttpOnly; Secure; SameSite=Strict")
```

**SameSite Options:**

| Value | Behavior |
|-------|----------|
| `Strict` | Cookie is only sent if the request originates from the same site. Most secure. |
| `Lax` | Sent on same-site requests and top-level GET navigations (clicking links). |
| `None` | Always sent. Requires the `Secure` flag to be set. Use with caution. |

**Recommended:** Use `Strict` for all authentication and session handling cookies. Use `Lax` for user-experience-related cookies where cross-site links might need to maintain state.

**Tools:** Browser DevTools (Application tab -> Cookies), OWASP ZAP, Manual review
