---
title: Invalidate Session On Logout
impact: MEDIUM
impactDescription: ensures logout actually terminates access and prevents session reuse
tags: session, logout, invalidation, security, kotlin
---

## Invalidate Session On Logout

If the server does not explicitly invalidate the session on logout, the session token remains valid. An attacker who has stolen the session token (e.g., via XSS or physical access) can continue using it even after the user thinks they have logged out.

**Incorrect (client-only logout):**

```kotlin
// Frontend-only logout (token still valid on server!)
fun logout() {
    localStorage.removeItem("token")
    navigateToLogin()
}

// Server doesn't invalidate session
@PostMapping("/logout")
fun logout(): ResponseEntity<Any> {
    return ResponseEntity.ok("Success") // Session still active in Redis/DB!
}
```

**Correct (server-side invalidation):**

```kotlin
// Spring Security (Handles most of this automatically)
// http.logout().logoutUrl("/logout").invalidateHttpSession(true).deleteCookies("JSESSIONID")

@PostMapping("/api/logout")
fun logout(request: HttpServletRequest, response: HttpServletResponse): ResponseEntity<Any> {
    // 1. Invalidate Session
    request.session?.invalidate()
    
    // 2. If using JWT - add to a blacklist (Redis) until expiry
    val token = extractToken(request)
    tokenBlacklist.add(token)

    // 3. Clear cookies explicitly
    val cookie = Cookie("session", null).apply {
        maxAge = 0
        path = "/"
        isHttpOnly = true
        isSecure = true
    }
    response.addCookie(cookie)

    // 4. Prevent Caching of sensitive data
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate")
    
    return ResponseEntity.ok("Logged out")
}

// Ktor
post("/logout") {
    call.sessions.clear<UserSession>()
    call.respond(HttpStatusCode.OK)
}
```

**Best Practices:**
- Always invalidate the session on the server side.
- Clear authentication cookies with appropriate flags (`HttpOnly`, `Secure`).
- If using stateless JWTs, maintain a short-lived blacklist for logged-out tokens.
- Clear all sensitive data from client-side storage (`localStorage`, `sessionStorage`).

**Tools:** Spring Security Logout, Ktor Sessions, Manual Audit
