Web application security · 5 MIN READ

Session cookies: lock down the attributes and keep the session's lifetime on the server

Issue a __Host- session cookie with the right attributes, rotate the ID at login and enforce idle, absolute and logout expiry in a server-side store.

A session cookie is a bearer credential: whoever presents it is the user until the server decides otherwise. Its attributes control where the browser sends it and whether page scripts can read it; the server-side record controls how long it is honored. Getting either half wrong produces familiar incidents: a cookie copied out by an injected script, a session an attacker fixed before the victim logged in, or a logout that only deleted the browser's copy.

security · A MAP OF THE IDEA

  1. Issue random ID
  2. Rotate at login
  3. Enforce idle + absolute
  4. Delete on logout

Useful when

  • The prefix and attributes are enforced by the browser on every request.
  • Server-side expiry and deletion work even when a cookie was copied.

Watch out

  • Max-Age and Expires are instructions to the browser, not enforcement.
  • An in-memory store is per-process and loses every session on restart.

Implementation & operation cost: A shared session store with TTLs and a user-to-session index, plus one lookup on every authenticated request.

01

What each attribute buys

HttpOnly hides the cookie from document.cookie, so an XSS payload cannot copy it out, although it can still send requests while the page is open. Secure stops the browser from sending it over plain HTTP. SameSite=Lax keeps it off cross-site subrequests and form posts, which narrows CSRF exposure. Path=/ with no Domain attribute makes a host-only cookie that is not sent to sibling subdomains. The __Host- name prefix turns those properties into browser-enforced rules: a cookie named __Host-session is rejected unless it is Secure, set from a secure origin, has Path=/ and carries no Domain, so a compromised subdomain cannot plant or overwrite it. Go's net/http does not check prefix rules; the browser does.

02

A store that owns expiry and rotation

The program models a session store with an injected clock, so expiry is deterministic. The cookie carries only a random ID from crypto/rand.Text; the user, the creation time and the last activity live on the server. It walks through a login that follows a planted pre-login ID, idle expiry, absolute expiry of a busy session and logout, and prints the Set-Cookie headers with the random value masked.

go
package main

import (
	"crypto/rand"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync"
	"time"
)

const cookieName = "__Host-session"

var (
	errNoSession   = errors.New("session not found")
	errIdleExpired = errors.New("session expired (idle)")
	errAbsExpired  = errors.New("session expired (absolute)")
)

type session struct {
	userID   string
	created  time.Time
	lastSeen time.Time
}

// store owns every session; the cookie only carries an unguessable key.
type store struct {
	mu       sync.Mutex
	byID     map[string]*session
	now      func() time.Time
	idle     time.Duration
	absolute time.Duration
}

func (s *store) create(userID string) string {
	s.mu.Lock()
	defer s.mu.Unlock()
	id := rand.Text() // at least 128 bits from crypto/rand
	t := s.now()
	s.byID[id] = &session{userID: userID, created: t, lastSeen: t}
	return id
}

func (s *store) lookup(id string) (string, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	sess, ok := s.byID[id]
	if !ok {
		return "", errNoSession
	}
	t := s.now()
	switch {
	case t.Sub(sess.created) > s.absolute:
		delete(s.byID, id)
		return "", errAbsExpired
	case t.Sub(sess.lastSeen) > s.idle:
		delete(s.byID, id)
		return "", errIdleExpired
	}
	sess.lastSeen = t
	return sess.userID, nil
}

// login discards the pre-login session and issues a fresh ID.
func (s *store) login(oldID, userID string) string {
	s.destroy(oldID)
	return s.create(userID)
}

func (s *store) destroy(id string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.byID, id)
}

func sessionCookie(id string, maxAge int) *http.Cookie {
	return &http.Cookie{
		Name:     cookieName,
		Value:    id,
		Path:     "/",
		MaxAge:   maxAge,
		HttpOnly: true,
		Secure:   true,
		SameSite: http.SameSiteLaxMode,
	}
}

func setCookieHeader(c *http.Cookie) string {
	rec := httptest.NewRecorder()
	http.SetCookie(rec, c)
	h := rec.Header().Get("Set-Cookie")
	if c.Value != "" {
		h = strings.Replace(h, c.Value, "<id>", 1)
	}
	return h
}

func show(label string, st *store, id string) {
	user, err := st.lookup(id)
	if err != nil {
		fmt.Printf("%s: %v\n", label, err)
		return
	}
	fmt.Printf("%s: ok %s\n", label, user)
}

func main() {
	clock := time.Date(2026, 1, 5, 9, 0, 0, 0, time.UTC)
	st := &store{
		byID:     map[string]*session{},
		now:      func() time.Time { return clock },
		idle:     30 * time.Minute,
		absolute: 8 * time.Hour,
	}

	// An attacker can plant a pre-login ID in the victim's browser.
	planted := st.create("")
	id := st.login(planted, "user-42")
	fmt.Println(setCookieHeader(sessionCookie(id, int(st.absolute.Seconds()))))
	show("planted pre-login ID", st, planted)
	fmt.Printf("new ID differs: %t, length %d\n", id != planted, len(id))

	clock = clock.Add(20 * time.Minute)
	show("after 20m", st, id)
	clock = clock.Add(31 * time.Minute)
	show("after 31m without a request", st, id)

	id = st.login("", "user-42")
	for range 19 { // a request every 25 minutes keeps the idle timer fresh
		clock = clock.Add(25 * time.Minute)
		if _, err := st.lookup(id); err != nil {
			fmt.Println("unexpected:", err)
		}
	}
	show("busy session at 7h55m", st, id)
	clock = clock.Add(25 * time.Minute)
	show("busy session at 8h20m", st, id)

	id = st.login("", "user-42")
	st.destroy(id) // logout invalidates the record on the server
	show("replayed cookie after logout", st, id)
	fmt.Println(setCookieHeader(sessionCookie("", -1)))
}
Read the code

http.SetCookie renders the attributes in a fixed order; Max-Age=28800 matches the eight-hour absolute limit, but the server never relies on the browser forgetting the cookie. login destroys the old record before creating a new one, so the planted ID is dead and the user gets a fresh 26-character base32 ID; rand.Text guarantees at least 128 bits of randomness and may return longer strings in future releases. lookup checks the absolute limit against created and the idle limit against lastSeen, deletes expired records and refreshes lastSeen only on success. The busy session survives nineteen requests 25 minutes apart and still ends after eight hours. destroy removes the record, so a copied cookie replayed after logout finds nothing, and the final header, empty with Max-Age=0, asks the browser to drop its copy.

03

Rotate the ID on every privilege change

Session fixation works when an application keeps the identifier it issued before login. An attacker obtains a valid anonymous ID, gets it into the victim's browser through a crafted link, a sibling subdomain or an injected header, and waits; once the victim authenticates, the attacker's copy of the same ID is logged in too. Issuing a new ID at login, and again whenever privileges rise, for example after step-up authentication or entering an admin mode, makes every earlier copy worthless. Carry over only the pre-login data you choose, such as a cart, by copying it into the new record. The __Host- prefix makes planting harder; rotation makes it pointless. Use both.

04

Set and clear the cookie in net/http and Gin

Gin's positional c.SetCookie(name, value, maxAge, path, domain, secure, httpOnly) takes SameSite from a separate c.SetSameSite call and URL-escapes the value, which makes a missing attribute easy to overlook; c.SetCookieData accepts a complete http.Cookie. Leave Domain empty: setting it to example.com widens the cookie to every subdomain and is forbidden with the __Host- prefix. Over plain HTTP on a development hostname the browser drops a Secure cookie, so run development over HTTPS rather than adding a flag that disables Secure and can leak into a release.

go
// net/http
http.SetCookie(w, &http.Cookie{
	Name: "__Host-session", Value: id, Path: "/",
	MaxAge: 8 * 60 * 60, HttpOnly: true, Secure: true,
	SameSite: http.SameSiteLaxMode,
})

// Gin: SetCookieData takes the whole cookie, including SameSite.
c.SetCookieData(&http.Cookie{
	Name: "__Host-session", Value: id, Path: "/",
	MaxAge: 8 * 60 * 60, HttpOnly: true, Secure: true,
	SameSite: http.SameSiteLaxMode,
})
Read the code

This fragment runs inside your own handler. MaxAge is in seconds, and a negative value emits Max-Age=0, which deletes the cookie. Both calls produce the same header, so a test can assert on the Set-Cookie string exactly as the program does. Gin's SetCookieData fills in Path and SameSite only when they are empty, so the explicit values above are what is sent.

05

Expiry and logout belong to the server

An idle timeout limits how long an abandoned, unlocked laptop stays logged in; an absolute timeout limits how long a stolen cookie is useful even if the thief keeps it busy. Choose both from the application's risk, for example 30 minutes idle and 8 hours absolute for an admin console, and enforce them where the record lives, not through Max-Age or Expires, which only instruct an honest browser. Logout must delete the server record and then clear the cookie; clearing only the cookie leaves every copied value valid. Plan the other invalidations too: a password change or account lock should end all of the user's sessions, which needs an index from user to session IDs. A real store is Redis or a database table with TTLs and that index; the in-memory map here is a model that loses everything on restart and is not shared between replicas.

06

Review checklist

Read the Set-Cookie header in a test rather than the struct you meant to send, and assert HttpOnly, Secure, SameSite, Path=/ and the __Host- name. Assert that the ID changes across login and that the old ID fails afterwards. Advance a fake clock past the idle and the absolute limits and expect rejection, and replay a cookie after logout. Keep session IDs out of logs, URLs and analytics events. If a leaked session table would be serious, store a hash of each ID instead of the ID itself, a token-design decision covered elsewhere in this course.

TAKE THIS WITH YOU

Name the cookie __Host-, set HttpOnly, Secure, SameSite and Path=/, issue a fresh crypto/rand ID at every login and enforce idle, absolute and logout expiry in the server-side store.

Check your understanding

Why must a login handler issue a new session ID instead of attaching the user to the current one?

Go to the source

Progress stays in this browser. No account needed.