Sessions
suggest changeHTTP is stateless: every request stands alone. A session ties requests from one browser together, so the server can remember that this visitor logged in as alice, has 3 items in the cart, and should see a "Saved!" message on the next page.
There are two ways to keep session data:
- server-side sessions: the browser gets a cookie with a random, unguessable session ID. The data lives on the server (in memory, a database or Redis), keyed by that ID.
- client-side (cookie) sessions: the data itself is stored in the cookie, signed and usually encrypted so the user can't read or change it.
Server-side sessions are the usual choice for logins, because deleting the session on the server logs the user out right away, even if someone copied the cookie. This article builds a small but complete session manager with only the standard library, then shows how to persist sessions in SQLite and how to use the popular alexedwards/scs and gorilla/sessions packages.
The basics of cookies (attributes, signing, encryption) are covered in Cookies.
What a session manager must do
On every request it has to:
- read the session ID from the cookie and load the session from the store
- reject sessions that are expired: idle for too long, or older than a maximum lifetime
- make the session available to the handler (through the request's
context.Context) - save the session after the handler changes it, and send a cookie when the ID is new
It must also support:
- renewing the ID on login, so an attacker who planted a session ID in the victim's browser can't use it (session fixation)
- destroying the session on logout, on the server as well as in the browser
The session and the store
A session is an ID, a map of values and two timestamps. The store is a small interface, so we can swap the in-memory implementation for a database later:
package main
import (
"errors"
"maps"
"sync"
"time"
)
type Session struct {
ID string
Values map[string]any
CreatedAt time.Time
LastSeen time.Time
// per-request state, not persisted
isNew bool
modified bool
destroyed bool
oldID string
}
var ErrNotFound = errors.New("session not found")
type Store interface {
Get(id string) (*Session, error) // ErrNotFound if there's no such session
Save(s *Session) error
Delete(id string) error
}
type MemoryStore struct {
mu sync.Mutex
sessions map[string]Session
}
func NewMemoryStore() *MemoryStore {
return &MemoryStore{sessions: map[string]Session{}}
}
func (m *MemoryStore) Get(id string) (*Session, error) {
m.mu.Lock()
defer m.mu.Unlock()
s, ok := m.sessions[id]
if !ok {
return nil, ErrNotFound
}
s.Values = maps.Clone(s.Values) // the caller gets its own copy
return &s, nil
}
func (m *MemoryStore) Save(s *Session) error {
m.mu.Lock()
defer m.mu.Unlock()
// copy only the persistent fields
m.sessions[s.ID] = Session{
ID: s.ID,
Values: maps.Clone(s.Values),
CreatedAt: s.CreatedAt,
LastSeen: s.LastSeen,
}
return nil
}
func (m *MemoryStore) Delete(id string) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.sessions, id)
return nil
}
func (m *MemoryStore) Len() int {
m.mu.Lock()
defer m.mu.Unlock()
return len(m.sessions)
}
Each request works on its own copy of the session. Two concurrent requests from the same browser don't step on each other's maps, but the one that saves last wins. That's how most session libraries behave, and it's fine for typical session data. Note that maps.Clone is a shallow copy: if you store a map or a pointer in Values, treat it as read-only and replace it instead of modifying it.
In Save I copy only the persistent fields. My first version copied the whole struct and stored the isNew flag along with it, so every loaded session looked new and Renew never deleted the old ID. A database store doesn't have this problem, because it only writes the columns it has.
The manager and middleware
The manager loads the session in a middleware and stores it in the request context. See HTTP server middleware and Context with value for those patterns.
The tricky part is saving. The session cookie is a response header, and headers can't be changed after the handler writes the first byte of the body. So we can't simply save after next.ServeHTTP returns. Instead we wrap the http.ResponseWriter and commit the session right before the first WriteHeader or Write:
package main
import (
"context"
"crypto/rand"
"errors"
"log"
"net/http"
"time"
)
type Manager struct {
Store Store
CookieName string
IdleTimeout time.Duration // expire after this long without requests
MaxLifetime time.Duration // expire this long after creation, no matter what
now func() time.Time
}
func NewManager(store Store) *Manager {
return &Manager{
Store: store,
CookieName: "__Host-session",
IdleTimeout: 30 * time.Minute,
MaxLifetime: 12 * time.Hour,
now: time.Now,
}
}
type ctxKey struct{}
func (m *Manager) newSession() *Session {
now := m.now()
return &Session{
ID: rand.Text(), // 128 random bits, Go 1.24+
Values: map[string]any{},
CreatedAt: now,
LastSeen: now,
isNew: true,
}
}
func (m *Manager) load(r *http.Request) (*Session, error) {
c, err := r.Cookie(m.CookieName)
if err != nil {
return m.newSession(), nil // no cookie
}
s, err := m.Store.Get(c.Value)
if errors.Is(err, ErrNotFound) {
return m.newSession(), nil // unknown or deleted session
}
if err != nil {
return nil, err
}
now := m.now()
if now.Sub(s.LastSeen) > m.IdleTimeout || now.Sub(s.CreatedAt) > m.MaxLifetime {
if err := m.Store.Delete(s.ID); err != nil {
return nil, err
}
return m.newSession(), nil
}
return s, nil
}
func (m *Manager) commit(w http.ResponseWriter, s *Session) error {
if s.oldID != "" {
if err := m.Store.Delete(s.oldID); err != nil {
return err
}
}
if s.destroyed {
http.SetCookie(w, &http.Cookie{
Name: m.CookieName, Value: "", Path: "/", MaxAge: -1,
HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode,
})
return m.Store.Delete(s.ID)
}
if s.isNew && !s.modified {
return nil // don't store empty sessions of anonymous visitors
}
now := m.now()
// saving on every request means a write per request; once a minute is enough
if s.modified || now.Sub(s.LastSeen) > time.Minute {
s.LastSeen = now
if err := m.Store.Save(s); err != nil {
return err
}
}
if s.isNew || s.oldID != "" {
http.SetCookie(w, &http.Cookie{
Name: m.CookieName,
Value: s.ID,
Path: "/",
Expires: s.CreatedAt.Add(m.MaxLifetime),
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteLaxMode,
})
}
return nil
}
// commitWriter saves the session right before the first byte of the
// response is written, because after that we can no longer set a cookie.
type commitWriter struct {
http.ResponseWriter
commit func()
done bool
}
func (cw *commitWriter) doCommit() {
if !cw.done {
cw.done = true
cw.commit()
}
}
func (cw *commitWriter) WriteHeader(code int) {
cw.doCommit()
cw.ResponseWriter.WriteHeader(code)
}
func (cw *commitWriter) Write(b []byte) (int, error) {
cw.doCommit()
return cw.ResponseWriter.Write(b)
}
// Unwrap lets http.ResponseController reach the underlying writer.
func (cw *commitWriter) Unwrap() http.ResponseWriter { return cw.ResponseWriter }
func (m *Manager) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s, err := m.load(r)
if err != nil {
log.Printf("session load: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Add("Vary", "Cookie")
cw := &commitWriter{ResponseWriter: w}
cw.commit = func() {
if err := m.commit(w, s); err != nil {
log.Printf("session commit: %v", err)
}
}
ctx := context.WithValue(r.Context(), ctxKey{}, s)
next.ServeHTTP(cw, r.WithContext(ctx))
cw.doCommit() // in case the handler didn't write anything
})
}
func session(r *http.Request) *Session {
s, ok := r.Context().Value(ctxKey{}).(*Session)
if !ok {
panic("session middleware not installed")
}
return s
}
func Get(r *http.Request, key string) any {
return session(r).Values[key]
}
func Put(r *http.Request, key string, v any) {
s := session(r)
s.Values[key] = v
s.modified = true
}
// Pop returns the value and removes it; useful for flash messages.
func Pop(r *http.Request, key string) any {
s := session(r)
v, ok := s.Values[key]
if ok {
delete(s.Values, key)
s.modified = true
}
return v
}
// Renew gives the session a new ID and keeps the data. Call it on login
// and on any change of privilege to prevent session fixation.
func (m *Manager) Renew(r *http.Request) {
s := session(r)
if !s.isNew && s.oldID == "" {
s.oldID = s.ID
}
s.ID = rand.Text()
s.CreatedAt = m.now()
s.modified = true
}
// Destroy deletes the session from the store and the browser.
func Destroy(r *http.Request) {
s := session(r)
s.destroyed = true
s.Values = map[string]any{}
}
Design decisions worth pointing out:
- Two timeouts. The idle timeout logs out users who walked away from the computer. The absolute lifetime limits how long a stolen session ID is useful, even if the thief keeps it active.
- The expiry check is done on the server. The cookie's
Expiresis only a hint to the browser; an attacker can send the cookie whenever they want. - Anonymous visitors don't create sessions until something is stored. Otherwise every bot and crawler adds a row to your store.
LastSeenis written at most once a minute unless data changed, which keeps a database store from doing a write on every request.__Host-prefix tells the browser to accept the cookie only if it'sSecure, hasPath=/and noDomain, so a subdomain can't overwrite it.Vary: Cookiestops shared caches from serving one user's page to another.- If saving fails while the response is being written, we can only log it: the status code may already be on its way. If you need to report such errors to the client, save explicitly in the handler before writing the response.
Using the manager
Handlers call Get, Put and Pop, plus Renew on login and Destroy on logout. To show the whole flow, the program below starts an httptest TLS server on a random port and talks to it with a client that has a cookie jar, just like a browser. The Secure cookie attribute requires HTTPS, so a plain httptest.NewServer would not get the cookie back.
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"strings"
)
func main() {
store := NewMemoryStore()
sm := NewManager(store)
mux := http.NewServeMux()
mux.HandleFunc("GET /visits", func(w http.ResponseWriter, r *http.Request) {
n, _ := Get(r, "visits").(int)
n++
Put(r, "visits", n)
fmt.Fprintf(w, "visits: %d", n)
})
mux.HandleFunc("POST /login", func(w http.ResponseWriter, r *http.Request) {
user := r.FormValue("user")
// ... verify the password here ...
sm.Renew(r)
Put(r, "user", user)
Put(r, "flash", "Welcome, "+user+"!")
http.Redirect(w, r, "/me", http.StatusSeeOther)
})
mux.HandleFunc("GET /me", func(w http.ResponseWriter, r *http.Request) {
user, ok := Get(r, "user").(string)
if !ok {
http.Error(w, "not logged in", http.StatusUnauthorized)
return
}
flash, _ := Pop(r, "flash").(string)
fmt.Fprintf(w, "user=%s visits=%v flash=%q", user, Get(r, "visits"), flash)
})
mux.HandleFunc("POST /logout", func(w http.ResponseWriter, r *http.Request) {
Destroy(r)
fmt.Fprint(w, "logged out")
})
srv := httptest.NewTLSServer(sm.Middleware(mux))
defer srv.Close()
// a client with a cookie jar behaves like a browser
client := srv.Client()
client.Jar, _ = cookiejar.New(nil)
u, _ := url.Parse(srv.URL)
do := func(method, path, form string) {
req, _ := http.NewRequest(method, srv.URL+path, strings.NewReader(form))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
cookie := "-"
if cs := client.Jar.Cookies(u); len(cs) > 0 {
cookie = cs[0].Value[:6]
}
fmt.Printf("%-4s %-7s %d %-46s cookie=%-6s stored=%d\n",
method, path, resp.StatusCode, strings.TrimSpace(string(body)), cookie, store.Len())
}
do("GET", "/me", "")
do("GET", "/visits", "")
do("GET", "/visits", "")
do("POST", "/login", "user=alice")
do("GET", "/me", "")
do("POST", "/logout", "")
do("GET", "/me", "")
}
GET /me 401 not logged in cookie=- stored=0
GET /visits 200 visits: 1 cookie=AXUV2R stored=1
GET /visits 200 visits: 2 cookie=AXUV2R stored=1
POST /login 200 user=alice visits=2 flash="Welcome, alice!" cookie=E7EMAK stored=1
GET /me 200 user=alice visits=2 flash="" cookie=E7EMAK stored=1
POST /logout 200 logged out cookie=- stored=0
GET /me 401 not logged in cookie=- stored=0
What happened:
- the first
/medidn't create a session, because nothing was stored /visitscreated a session; the visit count survived across requests- login kept the data (
visits=2) but changed the ID fromAXUV2R...toE7EMAK..., and the old session was deleted from the store - the client followed the 303 redirect to
/me, which showed the flash message once;Popremoved it, so the next/mehas an empty flash - logout deleted the session from the store and told the browser to delete the cookie
Testing timeouts and session fixation
Because the manager reads the time through its now field, a test can move a fake clock forward instead of sleeping for 12 hours. rec.Result().Cookies() and req.AddCookie let us replay the cookie like a browser would (see Testing HTTP requests):
package main
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestTimeouts(t *testing.T) {
sm := NewManager(NewMemoryStore())
clock := time.Date(2026, 10, 17, 9, 0, 0, 0, time.UTC)
sm.now = func() time.Time { return clock }
h := sm.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/login" {
sm.Renew(r)
Put(r, "user", "alice")
}
user, _ := Get(r, "user").(string)
w.Write([]byte(user))
}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", "/login", nil))
cookie := rec.Result().Cookies()[0]
// visit after the given time, return the user name from the session
visit := func(after time.Duration) string {
clock = clock.Add(after)
req := httptest.NewRequest("GET", "/", nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec.Body.String()
}
// active every 20 minutes: the idle timeout never triggers...
for i := range 36 { // 36 * 20m = 12h
if got := visit(20 * time.Minute); got != "alice" {
t.Fatalf("visit %d: logged out too early", i)
}
}
// ...but the absolute timeout does, 12 hours after login
if got := visit(20 * time.Minute); got != "" {
t.Errorf("after 12h20m: still logged in")
}
// a fresh login, then 31 minutes of inactivity
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", "/login", nil))
cookie = rec.Result().Cookies()[0]
if got := visit(29 * time.Minute); got != "alice" {
t.Errorf("after 29m idle: logged out")
}
if got := visit(31 * time.Minute); got != "" {
t.Errorf("after 31m idle: still logged in")
}
}
func TestSessionFixation(t *testing.T) {
sm := NewManager(NewMemoryStore())
h := sm.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/visit":
Put(r, "visited", true)
case "/login":
sm.Renew(r)
Put(r, "user", "alice")
}
user, _ := Get(r, "user").(string)
w.Write([]byte(user))
}))
// the attacker gets a valid session ID and plants it in the victim's browser
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/visit", nil))
planted := rec.Result().Cookies()[0]
// the victim logs in with the planted cookie
req := httptest.NewRequest("POST", "/login", nil)
req.AddCookie(planted)
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if cs := rec.Result().Cookies(); len(cs) == 0 || cs[0].Value == planted.Value {
t.Fatal("session ID not changed on login")
}
// the attacker's copy of the ID is now useless
req = httptest.NewRequest("GET", "/", nil)
req.AddCookie(planted)
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Body.String() != "" {
t.Errorf("attacker is logged in as %q", rec.Body.String())
}
}
$ go test -v
=== RUN TestTimeouts
--- PASS: TestTimeouts (0.00s)
=== RUN TestSessionFixation
--- PASS: TestSessionFixation (0.00s)
PASS
Comment out the sm.Renew(r) call in the handler of TestSessionFixation and it fails with session ID not changed on login.
Storing sessions in a database
The in-memory store loses all sessions on restart and doesn't work when you run more than one server. Implementing Store for a SQL database fixes both. This version uses SQLite through the pure-Go driver modernc.org/sqlite (no cgo needed), but the SQL works with small changes in PostgreSQL and MySQL too.
Two details matter:
- store a hash of the session ID, not the ID itself. Someone who gets a copy of the database (a leaked backup, an SQL injection) sees only SHA-256 hashes, which can't be turned back into working cookies. Session IDs are 128-bit random values, so a plain fast hash is enough here; this is not like password hashing.
- delete expired rows periodically. The manager rejects expired sessions, but rows of users who never came back stay in the table forever unless something removes them.
package main
import (
"bytes"
"context"
"crypto/sha256"
"database/sql"
"encoding/gob"
"encoding/hex"
"errors"
"log"
"time"
)
type SQLStore struct {
db *sql.DB
}
func NewSQLStore(db *sql.DB) (*SQLStore, error) {
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS sessions (
id_hash TEXT PRIMARY KEY,
data BLOB NOT NULL,
created_at INTEGER NOT NULL,
last_seen INTEGER NOT NULL
)`)
if err != nil {
return nil, err
}
return &SQLStore{db: db}, nil
}
// hashID: the database stores a hash of the ID, so someone who reads
// the database (or a backup) can't use its contents to log in.
func hashID(id string) string {
sum := sha256.Sum256([]byte(id))
return hex.EncodeToString(sum[:])
}
func (s *SQLStore) Get(id string) (*Session, error) {
var data []byte
var created, lastSeen int64
err := s.db.QueryRow(
`SELECT data, created_at, last_seen FROM sessions WHERE id_hash = ?`,
hashID(id)).Scan(&data, &created, &lastSeen)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
sess := &Session{
ID: id,
CreatedAt: time.Unix(created, 0),
LastSeen: time.Unix(lastSeen, 0),
}
if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&sess.Values); err != nil {
return nil, err
}
return sess, nil
}
func (s *SQLStore) Save(sess *Session) error {
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(sess.Values); err != nil {
return err
}
_, err := s.db.Exec(`INSERT INTO sessions (id_hash, data, created_at, last_seen)
VALUES (?, ?, ?, ?)
ON CONFLICT (id_hash) DO UPDATE SET data = excluded.data, last_seen = excluded.last_seen`,
hashID(sess.ID), buf.Bytes(), sess.CreatedAt.Unix(), sess.LastSeen.Unix())
return err
}
func (s *SQLStore) Delete(id string) error {
_, err := s.db.Exec(`DELETE FROM sessions WHERE id_hash = ?`, hashID(id))
return err
}
// DeleteExpired removes sessions that the manager would reject anyway.
func (s *SQLStore) DeleteExpired(idle, maxLifetime time.Duration) (int64, error) {
now := time.Now()
res, err := s.db.Exec(`DELETE FROM sessions WHERE last_seen < ? OR created_at < ?`,
now.Add(-idle).Unix(), now.Add(-maxLifetime).Unix())
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Cleanup runs DeleteExpired periodically until ctx is cancelled.
func (s *SQLStore) Cleanup(ctx context.Context, every, idle, maxLifetime time.Duration) {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
n, err := s.DeleteExpired(idle, maxLifetime)
if err != nil {
log.Printf("session cleanup: %v", err)
} else if n > 0 {
log.Printf("session cleanup: deleted %d sessions", n)
}
}
}
}
The values are serialized with encoding/gob. Basic types like string and int work out of the box; your own types must be registered with gob.Register(Cart{}) before they're stored in a session, otherwise Save fails with gob: type not registered for interface: main.Cart.
To use it, pass it to the manager and start the cleanup goroutine:
store, err := NewSQLStore(db)
if err != nil {
log.Fatal(err)
}
sm := NewManager(store)
go store.Cleanup(ctx, 10*time.Minute, sm.IdleTimeout, sm.MaxLifetime)
Redis is another common choice: SET with an expiration does the cleanup for you. For more on database/sql see Database connection pooling.
Using alexedwards/scs
scs is a mature session manager that works the same way as the code above: a LoadAndSave middleware, data in the request context, idle and absolute timeouts, RenewToken and Destroy. It also has ready-made stores for PostgreSQL, MySQL, SQLite, Redis, BoltDB and others (each a separate module, such as github.com/alexedwards/scs/postgresstore).
go get github.com/alexedwards/scs/v2@latest
package main
import (
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"strings"
"time"
"github.com/alexedwards/scs/v2"
)
var sm *scs.SessionManager
func login(w http.ResponseWriter, r *http.Request) {
// ... verify the password here ...
if err := sm.RenewToken(r.Context()); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
user := r.FormValue("user")
sm.Put(r.Context(), "user", user)
sm.Put(r.Context(), "flash", "Welcome, "+user+"!")
http.Redirect(w, r, "/me", http.StatusSeeOther)
}
func me(w http.ResponseWriter, r *http.Request) {
user := sm.GetString(r.Context(), "user")
if user == "" {
http.Error(w, "not logged in", http.StatusUnauthorized)
return
}
flash := sm.PopString(r.Context(), "flash")
fmt.Fprintf(w, "user=%s flash=%q", user, flash)
}
func logout(w http.ResponseWriter, r *http.Request) {
if err := sm.Destroy(r.Context()); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprint(w, "logged out")
}
func main() {
sm = scs.New() // in-memory store by default
sm.Lifetime = 12 * time.Hour
sm.IdleTimeout = 30 * time.Minute
sm.Cookie.Name = "__Host-session"
sm.Cookie.HttpOnly = true
sm.Cookie.Secure = true
sm.Cookie.SameSite = http.SameSiteLaxMode
mux := http.NewServeMux()
mux.HandleFunc("POST /login", login)
mux.HandleFunc("GET /me", me)
mux.HandleFunc("POST /logout", logout)
srv := httptest.NewTLSServer(sm.LoadAndSave(mux))
defer srv.Close()
client := srv.Client()
client.Jar, _ = cookiejar.New(nil)
for _, step := range []struct{ method, path, form string }{
{"GET", "/me", ""},
{"POST", "/login", "user=bob"},
{"GET", "/me", ""},
{"POST", "/logout", ""},
{"GET", "/me", ""},
} {
req, _ := http.NewRequest(step.method, srv.URL+step.path, strings.NewReader(step.form))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
panic(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("%-4s %-7s %d %s\n", step.method, step.path, resp.StatusCode,
strings.TrimSpace(string(body)))
}
}
GET /me 401 not logged in
POST /login 200 user=bob flash="Welcome, bob!"
GET /me 200 user=bob flash=""
POST /logout 200 logged out
GET /me 401 not logged in
Typed getters (GetString, GetInt, GetBool, GetTime...) return the zero value when the key is missing, and Pop* variants read and delete in one step. To switch to a database, set sm.Store to one of the store implementations.
Cookie sessions with gorilla/sessions
gorilla/sessions offers both server-side stores and a CookieStore that keeps the whole session in a signed and encrypted cookie. No storage is needed on the server, which makes scaling trivial:
package main
import (
"crypto/rand"
"fmt"
"net/http"
"net/http/httptest"
"github.com/gorilla/sessions"
)
func main() {
// load these from configuration; random keys log everyone out on restart
hashKey := make([]byte, 32) // HMAC-SHA256 signing
blockKey := make([]byte, 32) // AES-256 encryption
rand.Read(hashKey)
rand.Read(blockKey)
store := sessions.NewCookieStore(hashKey, blockKey)
store.Options = &sessions.Options{
Path: "/",
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteLaxMode, // the default is None
}
// sets Options.MaxAge and the maximum age checked inside the signed value
store.MaxAge(12 * 3600)
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sess, err := store.Get(r, "app-session")
if err != nil {
// invalid or tampered cookie: Get still returns a new, empty session
fmt.Println("decode error:", err)
}
n, _ := sess.Values["visits"].(int)
sess.Values["visits"] = n + 1
if err := sess.Save(r, w); err != nil { // must be called before writing the body
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "visits: %d", n+1)
})
var cookie *http.Cookie
for range 3 {
req := httptest.NewRequest("GET", "/", nil)
if cookie != nil {
req.AddCookie(cookie)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
cookie = rec.Result().Cookies()[0]
fmt.Printf("%s cookie size: %d bytes\n", rec.Body, len(cookie.Value))
}
// a modified cookie is rejected
b := []byte(cookie.Value)
if b[10] == 'A' { // change one character
b[10] = 'B'
} else {
b[10] = 'A'
}
cookie.Value = string(b)
req := httptest.NewRequest("GET", "/", nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Println(rec.Body)
}
visits: 1 cookie size: 168 bytes
visits: 2 cookie size: 168 bytes
visits: 3 cookie size: 168 bytes
decode error: securecookie: the value is not valid
visits: 1
Unlike scs, gorilla/sessions doesn't save automatically: you call sess.Save(r, w) yourself, before writing the response body.
The trade-offs of cookie sessions:
- you can't log a user out on the server. Deleting the cookie in the browser doesn't help if the cookie was stolen: it's valid until it expires (securecookie checks the timestamp inside the value against the age set with
store.MaxAge). If that matters, keep a server-side "sessions valid after" timestamp per user, which brings back a database lookup. - size: browsers limit a cookie to about 4 KB, and the cookie is sent with every request, including requests for images and CSS.
- key rotation:
NewCookieStoreaccepts several key pairs; new cookies use the first pair and old cookies are still decoded with the others.
Sessions and CSRF
A browser sends the session cookie with every request to your site, including requests triggered by a form on an attacker's page. That's cross-site request forgery (CSRF). SameSite=Lax already stops cookies on cross-site POST requests in modern browsers, and since Go 1.25 the standard library has http.CrossOriginProtection, which rejects cross-origin state-changing requests based on the Sec-Fetch-Site and Origin headers that browsers send:
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func main() {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "ok")
})
cop := http.NewCrossOriginProtection()
protected := cop.Handler(h)
try := func(name, method, header, value string) {
req := httptest.NewRequest(method, "https://example.com/transfer", nil)
if header != "" {
req.Header.Set(header, value)
}
rec := httptest.NewRecorder()
protected.ServeHTTP(rec, req)
fmt.Printf("%-28s %d\n", name, rec.Code)
}
try("same-origin POST", "POST", "Sec-Fetch-Site", "same-origin")
try("cross-site POST", "POST", "Sec-Fetch-Site", "cross-site")
try("cross-site GET", "GET", "Sec-Fetch-Site", "cross-site")
try("POST, other Origin", "POST", "Origin", "https://evil.example")
try("POST from curl (no headers)", "POST", "", "")
}
same-origin POST 200
cross-site POST 403
cross-site GET 200
POST, other Origin 403
POST from curl (no headers) 200
GET, HEAD and OPTIONS requests are always allowed, so never change state in a GET handler. Requests without either header aren't from a browser and can't carry a victim's cookies against their will, so they pass. Wrap the session middleware's handler with it: cop.Handler(sm.Middleware(mux)). More on this in Application security.
Checklist
- generate session IDs with
crypto/rand(rand.Text()), nevermath/rand, and never derive them from the user ID or time - use
HttpOnly,Secure,SameSite=Lax(orStrict) and the__Host-prefix on the session cookie - renew the session ID on login and on any privilege change; destroy the session on logout
- enforce both an idle timeout and an absolute lifetime on the server; the cookie's expiration is just a hint
- store sessions in a database or Redis when you have more than one server or want sessions to survive restarts; hash the IDs at rest and delete expired rows
- don't put session IDs in URLs: they end up in logs, browser history and
Refererheaders - don't log session IDs or full
Cookieheaders - when a user changes their password, delete their other sessions (this needs an index from user to sessions in your store)
Summary
- a session links requests from one browser; the cookie holds a random ID and the server holds the data
- a session manager is a middleware that loads the session into the request context and saves it before the response headers are sent
Renew(on login) prevents session fixation;Destroy(on logout) deletes the session on the server and in the browser- the store is a small interface (
Get,Save,Delete); an in-memory map is fine for development, SQL or Redis for production alexedwards/scsis a full implementation of the same design with many stores;gorilla/sessionsadds encrypted cookie sessions, which need no server storage but can't be revoked- combine sessions with
SameSitecookies andhttp.CrossOriginProtectionto defend against CSRF