---
title: Re-authenticate For Long-lived Sessions
impact: MEDIUM
impactDescription: ensures continuous user identity verification and reduces the window for session hijacking
tags: session, authentication, timeout, reauthentication, security, kotlin
---

## Re-authenticate For Long-lived Sessions

Long-lived sessions (e.g., "Remember Me" for 30 days) are convenient but increase the risk that a stolen session token remains useful to an attacker for a long time. Periodic re-authentication for the entire session or specific sensitive actions ensures the original user is still in control.

**Incorrect (sessions never expire or are too long without checks):**

```kotlin
// Infinite session age
sessionConfig.cookie.maxAge = -1 

// No re-authentication for critical tasks
@PostMapping("/user/change-password")
fun changePassword(@RequestBody req: NewPasswordReq) {
    // Only checks if session is valid, doesn't ask for old password again
    userService.updatePassword(currentUserId, req.newPassword)
}
```

**Correct (periodic re-authentication and step-up auth):**

```kotlin
val SESSION_MAX_AGE_MS = 24 * 60 * 60 * 1000L // 1 day
val REAUTH_INTERVAL_MS = 4 * 60 * 60 * 1000L  // 4 hours

// Middleware/Interceptor for checking last auth time
fun checkReauthNeeded(session: UserSession): Boolean {
    val lastAuth = session.lastAuthenticatedAt ?: 0L
    val now = System.currentTimeMillis()
    
    return (now - lastAuth) > REAUTH_INTERVAL_MS
}

// For sensitive operations (Step-up Authentication)
@PostMapping("/user/delete-account")
fun deleteAccount(@RequestBody request: DeleteAccountRequest) {
    // REQUIRE the current password again, even if the session is valid
    if (!authService.verifyPassword(currentUserId, request.currentPassword)) {
        throw AccessDeniedException("Recent password verification required")
    }
    
    userService.delete(currentUserId)
}
```

**Best Practices:**
- **Inactivity Timeout:** Invalidate sessions after an idle period (e.g., 30 minutes).
- **Absolute Timeout:** Force a full logout after a fixed period (e.g., 12 or 24 hours), regardless of activity.
- **Step-up Auth:** Require re-authentication (Password, OTP, or Biometric) for highly sensitive actions like changing security settings, financial transfers, or accessing personal info.

**Tools:** Spring Security (ConcurrentSessionFilter, RememberMe), Ktor Sessions, Manual Audit
