---
title: Re-authenticate For Long-lived Sessions
impact: MEDIUM
impactDescription: ensures continuous user identity verification
tags: session, authentication, timeout, reauthentication, security
---

## Re-authenticate For Long-lived Sessions

Long-running sessions may be hijacked. Periodic re-authentication ensures the original user is still present.

**Incorrect (sessions never expire or stay valid indefinitely):**

```go
// Session cookie created without expiry or with extremely long duration
cookie := &http.Cookie{
    Name:  "session",
    Value: token,
} // Defaults to session-only browsers, but logic may never check "age" on server
```

**Correct (periodic re-authentication/expiry):**

```go
const SessionMaxAge = 24 * time.Hour
const ReauthInterval = 4 * time.Hour

func authMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        session := getSession(r)
        
        // Check if session is too old
        if time.Since(session.CreatedAt) > SessionMaxAge {
            http.Error(w, "Session expired", 401)
            return
        }
        
        // Check if re-authentication is required for sensitive routes
        if time.Since(session.LastAuthenticatedAt) > ReauthInterval {
            session.RequireReauth = true
        }
        
        next.ServeHTTP(w, r)
    })
}

// Handler for sensitive operation
func SensitiveHandler(w http.ResponseWriter, r *http.Request) {
    session := getSession(r)
    if session.RequireReauth {
         http.Error(w, "Re-authentication required", 401)
         return
    }
    // ...
}
```

**Tools:** Session libraries (e.g., `scs`, `gorilla/sessions`), Manual review
