Skip to content

Authentication in Go: Argon2/bcrypt, Sessions, JWT, Middleware, CSRF, Sanitization, Password Reset ​

"Once an authenticated session has been established, the session ID (or token) is temporarily equivalent to the strongest authentication method used by the application, such as username and password, passphrases, one-time passwords (OTP), client-based digital certificates, smartcards, or biometrics (such as fingerprint or eye retina)." — OWASP Session Management Cheat Sheet

Summary: Authentication in a Go service is a chain of small, separately testable pieces: a slow salted password hash (Argon2id or bcrypt) checked in constant time, a credential that carries the result to the next request (a server-side session behind a __Host- cookie, or a short-lived JWT plus a rotating refresh token), a middleware that puts the verified identity into the request context, an authorization check inside every handler, CSRF and output-encoding defences for browsers, and the flows around the edges (password reset, email verification, lockout, TOTP, logout) where most real breaches happen. Focus: golang.org/x/crypto/argon2 and bcrypt, RFC 9106 and OWASP parameters, the PHC string format, crypto/subtle, salts and peppers, NIST SP 800-63B-4 password rules, crypto/rand session IDs, cookie flags and prefixes, rotation and timeouts, alexedwards/scs and gorilla/sessions, golang-jwt/jwt/v5 with EdDSA, claim validation and kid rotation, alg confusion, refresh token rotation and revocation, JWKS, x/oauth2 and go-oidc, context identity, per-handler authorization (IDOR), CSRF tokens and Go 1.25 http.CrossOriginProtection, validation vs sanitization (bluemonday) vs html/template escaping, reset and verification tokens, lockout and rate limiting, timing attacks, pquerna/otp, passkeys with go-webauthn, logout, and how Laravel's starter kits, Fortify and Sanctum package the same decisions. Learning goal: Build a login, session and token layer in Go from the standard library plus a handful of well-known packages, explain every flag and parameter you set, and recognise the dozen classic bugs (fast hashes, == on secrets, user enumeration, session fixation, alg trust, missing aud, IDOR, CSRF on cookie auth, reset tokens stored in plaintext, logout that only deletes a cookie) on sight.

This page owns authentication as a Go developer implements it: the code, the packages, the parameters and the order of the checks. It does not re-teach its neighbours. The hash primitives, HMAC, HKDF and crypto/rand as APIs are in Hashing & Crypto; password storage and token signing as concepts in Password Hashing & Signed Tokens; the middleware pattern, security headers, CORS and the full http.CrossOriginProtection walkthrough in Middlewares; ServeMux routing and r.PathValue in net/http; forms, flash messages and template layouts in html/template; rate-limiting algorithms in Rate Limiting in Go. The system-level designs are on the system-design side: Authentication: Passwords, MFA & Sessions, JWT Deep Dive, OAuth2, OIDC & SSO, Web Sessions, Cookies & CORS and OWASP Top 10.

Facts below were checked against the Go 1.27 standard-library source on go.dev (crypto/subtle, crypto/rand, crypto/hmac, net/http cookie.go, csrf.go and server.go, html/template; pkg.go.dev returns 403 to scripted fetches), the Go 1.22, 1.24 and 1.25 release notes, the source of golang.org/x/crypto (argon2, bcrypt), golang-jwt/jwt/v5, alexedwards/scs/v2, gorilla/sessions, pquerna/otp, microcosm-cc/bluemonday, coreos/go-oidc/v3, golang.org/x/oauth2, go-webauthn/webauthn and MicahParks/keyfunc, RFC 9106 (Argon2), RFC 7515/7517/7518/7519 (JOSE and JWT), RFC 8725 (JWT best current practices), RFC 9068, RFC 9700 (OAuth 2.0 security BCP), RFC 6238 and 4226 (TOTP, HOTP), RFC 6265, the C2SP PHC string spec, NIST SP 800-63B-4, the OWASP Authentication, Session Management, Password Storage, CSRF, Forgot Password, JWT, MFA, XSS, Input Validation and Credential Stuffing cheat sheets, MDN's Set-Cookie and cookies guides, Filippo Valsorda's CSRF write-up, and the Laravel 13 authentication, Sanctum, hashing, passwords, verification, CSRF, session, rate-limiting, Fortify and starter-kit docs (plus the Laravel 11 starter-kit page and Laravel 12 release notes for Breeze). Snippets declare go 1.24 and pin golang.org/x/crypto v0.48.0 (v0.49.0 requires go 1.25), golang.org/x/time v0.14.0, github.com/golang-jwt/jwt/v5 v5.3.1, github.com/alexedwards/scs/v2 v2.9.0, github.com/pquerna/otp v1.5.0 and github.com/microcosm-cc/bluemonday v1.0.27; the one file that uses a Go 1.25 API carries a //go:build go1.25 line. All 14 packages were compiled, vetted and tested with -race on Go 1.27.4 (macOS, Apple M4 Pro); numbers in the lab are from that run.

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why authentication is a chain, not a functionWhy it exists
bcrypt, PHC, Argon2, JWT, TOTP: where each came fromWhere it comes from
A before/after login handlerGo
Password hashing: why slow, salts, peppersPassword hashing
Argon2id (x/crypto/argon2, RFC 9106 parameters), PHC string formatArgon2id
bcrypt (x/crypto/bcrypt, cost), the 72-byte limitbcrypt
Constant-time compare (crypto/subtle) and timing attacksConstant time
Password policy (NIST 800-63B)Password policy
Sessions (server-side store, session ID entropy crypto/rand, cookie flags HttpOnly Secure SameSite, rotation on login, idle/absolute timeout)Sessions
alexedwards/scs and gorilla/sessionsSession libraries
JWT (golang-jwt/jwt v5, HS256 vs RS256/ES256/EdDSA, claims validation exp/nbf/iat/aud/iss)JWT
Alg confusion, key rotation kidAlg confusion and kid
Short-lived access + refresh tokens, revocationRefresh and revocation
JWKS fetchingJWKS
OAuth2/OIDC client (x/oauth2, coreos/go-oidc) pointerOAuth2 and OIDC
Auth middleware and context identity; authorization check per handlerMiddleware and authorization
CSRF (double-submit cookie, SameSite, Origin check, Go 1.25 http.CrossOriginProtection)CSRF
Input sanitization vs validation vs output encoding (html/template auto-escaping, bluemonday)Validation, sanitization, encoding
Password reset flow (single-use token, hash stored, expiry, enumeration-safe responses)Password reset
Email verificationEmail verification
Account lockout and rate limitingLockout
MFA TOTP (pquerna/otp, RFC 6238), recovery codesTOTP
Passkeys/WebAuthn pointer (go-webauthn)Passkeys
Secure logoutLogout
Data layout, exact headers, error texts, schemaMechanics
The classic bugs and their fixesSolving the classic problems
What to use whenChoosing
Monolith to distributed systemIn architecture
Reproduce it on your machineLab
Laravel Breeze/Sanctum comparisonFor PHP/Laravel developers

Everything in one minute ​

The chain. Every authenticated request passes these links in this order; a weak link anywhere is the weakness of the whole. Each row is unpacked in the concept catalogue.

LinkGo toolPlain wordsClassic failure
Store the passwordargon2.IDKey / bcrypt.GenerateFromPasswordMake each guess cost milliseconds and megabytessha256(password), no salt
Check the passwordsubtle.ConstantTimeCompare, dummy hashSame time and same answer for every failure"no such user" vs "wrong password"
Throttle guessingper-account backoff + x/time/rate per IPOnline guessing becomes too slow to matterUnlimited attempts, or lockout as a DoS
Carry the result__Host- session cookie or a JWTA bearer secret now equals the passwordGuessable IDs, no rotation, alg trusted
Put identity in ctxcontext.WithValue with an unexported keyHandlers ask From(ctx), never re-parseIdentity read from a header or query
Authorizea check in the handler after loading the object"Is this invoice yours?"IDOR: any logged-in user reads any id
Defend the browserCSRF token, SameSite, CrossOriginProtection, html/templateOther sites cannot act or inject as the userCookie auth with no CSRF check, template.HTML(userInput)
End itdelete the server-side session, revoke refresh familyLogout works on the server, not only in the browserCookie cleared, session still valid

Sessions vs tokens.

PropertyServer-side session (cookie)JWT access token (bearer)
What the client holdsOpaque 256-bit random IDSigned JSON claims, about 350 bytes here
Verify a requestStore lookup by sha256(id)Signature + exp/iss/aud check, no lookup
Revoke nowDelete the rowNot possible before exp without a denylist
Typical lifetime30 min idle, 8-12 h absolute5-15 min access, days for the refresh token
CSRF exposureYes (browser sends cookies)No when sent in Authorization
XSS exposureHttpOnly hides the cookieA token in localStorage is readable by any script
FitsServer-rendered apps, first-party SPAsService-to-service, mobile, third-party APIs
Go packagestdlib, alexedwards/scs/v2, gorilla/sessionsgolang-jwt/jwt/v5, MicahParks/keyfunc

The parameters to remember.

KnobValueSource
Argon2id (OWASP minimum)m=19456 KiB (19 MiB), t=2, p=1OWASP Password Storage
Argon2id (RFC 9106 second option)t=3, p=4, m=64 MiB, 128-bit salt, 256-bit tagRFC 9106 section 4
bcrypt cost≥ 10 (OWASP); bcrypt.DefaultCost = 10; 12 here; 72-byte input limitOWASP, x/crypto
Salt≥ 32 bits (NIST); 128 bits hereNIST SP 800-63B-4
Session ID≥ 64 bits of entropy (OWASP); 256 bits here from crypto/randOWASP Session Management
Password length≥ 15 single-factor, ≥ 8 with MFA; allow ≥ 64; no composition rulesNIST SP 800-63B-4
Idle / absolute timeout2-5 min high-value, 15-30 min low-risk; 4-8 h absolute for an office dayOWASP Session Management
TOTP30 s step, 6 digits, at most one step of skew, reject replaysRFC 6238
Failed attempts≤ 100 consecutive per account before disabling (upper bound)NIST SP 800-63B-4
Reset tokenrandom, "sufficiently long" (128+ bits, the OWASP floor for generated session tokens), hashed, single use, short expiry (30-60 min)OWASP Forgot Password and Session Management, Laravel expire => 60

Why it exists ​

HTTP is stateless: every request arrives as a stranger. Authentication is how a server turns "someone typed a password once" into "this request comes from user 7", over and over, for hours, without asking for the password each time, while an attacker tries to guess the password, steal the thing that replaced it, ride the user's browser from another site, or simply read the user table from a backup. No single function solves that. It is a chain of decisions, and the code for each decision is small enough to get right, which is why this page breaks it into a dozen tested packages.

Easier to buildHarder to attack
sha256(password)Argon2id with a per-user salt and a cost you raise over time
if hash == storedsubtle.ConstantTimeCompare plus a dummy hash for unknown users
"No account with that email"One generic message for every failure
Session ID = auto-increment256 bits from crypto/rand, hashed in the store
Keep the session ID at loginRotate it on every privilege change
One long-lived JWT10-minute access token, rotating refresh token, revocation list
Trust the token's algAllow-list one algorithm per key
Check roles in middleware onlyLoad the object, then check ownership in the handler
Delete the cookie at logoutDelete the server-side state too

An everyday picture. A hotel. The front desk checks your passport once (password verification), then hands you a key card (session ID or token). The card opens your room for the length of your stay (lifetime) and stops working if you do not come back for a while (idle timeout). If you change rooms to a suite, you get a new card and the old one is cancelled (rotation on privilege change). A card is just a number that the door checks against the desk's list (server-side session); a fancier hotel prints your room and checkout date on the card itself and signs it, so doors can check it offline (JWT), but then it cannot cancel a lost card before checkout without telling every door (revocation). The card opens your room, not every room on the floor (authorization). And the desk never writes your passport number on a sticky note (password hashing).

Three common misunderstandings, up front ​

  1. "A JWT is more secure than a session cookie." It is a different trade: no lookup per request, in exchange for losing immediate revocation and taking on algorithm and key-management risks. For a browser talking to its own backend, a server-side session is usually the stronger and simpler choice.
  2. "Hashing passwords with SHA-256 and a salt is fine." A salt stops precomputed tables, not guessing; a GPU computes billions of SHA-256 hashes per second. Password hashes must be deliberately slow and memory-hard (Argon2id) or at least slow (bcrypt).
  3. "Authentication middleware means the endpoint is secure." Middleware proves who the caller is. Whether that caller may read invoice 1001 is a question only the handler that loaded invoice 1001 can answer; skipping it is Broken Object Level Authorization (IDOR), API1:2023, the first item of the OWASP API Security Top 10.

Where it comes from ​

bcrypt was published by Niels Provos and David Mazières at USENIX 1999 (the paper the x/crypto/bcrypt package comment links), with the idea that still defines password hashing: an adjustable work factor, so the hash can be made slower as hardware gets faster. The Password Hashing Competition picked Argon2 as its winner in 2015 (OWASP: "Argon2 was the winner of the 2015 Password Hashing Competition"), and RFC 9106 (September 2021) standardised it with concrete parameter advice. The PHC string format ($argon2id$v=19$m=...,t=...,p=...$salt$hash), started by the competition, has moved to C2SP as phc-strings.md. In Go both live in golang.org/x/crypto (the files' copyright lines say 2011 for bcrypt and 2017 for argon2); neither is in the standard library.

JWT is RFC 7519 (May 2015), built on JWS (RFC 7515), JWK (RFC 7517) and JWA (RFC 7518). The early libraries trusted the alg header, which produced the "none" and RS256-to-HS256 attacks catalogued in RFC 8725 (February 2020, the JWT Best Current Practices). In Go, dgrijalva/jwt-go was the de facto library until a team of maintainers forked it into golang-jwt/jwt (the README links the hand-over discussion); v5 "introduces major improvements to the validation of tokens", with a Validator and options such as WithLeeway, WithAudience and WithIssuer. TOTP is RFC 6238 (May 2011), on top of HOTP (RFC 4226). RFC 9700 (January 2025) made refresh token rotation or sender-constraining mandatory for public OAuth clients.

On the standard-library side, Go 1.22 added method and wildcard patterns to ServeMux, which is what lets per-route authorization read r.PathValue("id"). Go 1.24 made crypto/rand.Read "guaranteed not to fail" and added rand.Text for "cryptographically secure random text strings". Go 1.25 added http.CrossOriginProtection, which, in the release notes' words, "implements protections against Cross-Site Request Forgery (CSRF) by rejecting non-safe cross-origin browser requests". NIST SP 800-63B-4 (the 2025 revision of the digital identity guidelines) renamed "memorized secrets" to passwords, sets the single-factor minimum at 15 characters and keeps the ban on composition rules and forced periodic changes.

Go ​

Before ​

A login that works on a quiet day. It stores sha256(password) without a salt, compares with !=, tells the caller whether the email exists, keeps any session ID the browser sends (fixation) or mints a sequential one, sets a cookie without a single flag, and "logs out" by deleting the cookie in the browser only.

go
// Package before is a login that works on a quiet day and fails every audit:
// fast unsalted hash, == comparison, messages that reveal which accounts
// exist, a guessable session ID, a cookie without flags, no rotation, no
// throttling, and a logout that only deletes the cookie in the browser.
package before

import (
	"crypto/sha256"
	"encoding/hex"
	"net/http"
	"strconv"
	"sync"
)

type Server struct {
	mu       sync.Mutex
	users    map[string]string // email -> hex(sha256(password))
	sessions map[string]string // session id -> email
	next     int
}

func New() *Server {
	return &Server{users: map[string]string{}, sessions: map[string]string{}, next: 1000}
}

// Register stores sha256(password): no salt, no cost. Equal passwords give
// equal hashes, and a GPU tries billions of guesses per second.
func (s *Server) Register(email, pw string) string {
	sum := sha256.Sum256([]byte(pw))
	h := hex.EncodeToString(sum[:])
	s.mu.Lock()
	s.users[email] = h
	s.mu.Unlock()
	return h
}

func (s *Server) Login(w http.ResponseWriter, r *http.Request) {
	email, pw := r.PostFormValue("email"), r.PostFormValue("password")
	s.mu.Lock()
	stored, ok := s.users[email]
	s.mu.Unlock()
	if !ok {
		http.Error(w, "no account with that email", http.StatusNotFound) // enumeration
		return
	}
	sum := sha256.Sum256([]byte(pw))
	if hex.EncodeToString(sum[:]) != stored { // early-exit comparison
		http.Error(w, "wrong password", http.StatusUnauthorized)
		return
	}
	// Keep any session id the client already had (fixation), or mint a
	// sequential one (guessable).
	id := ""
	if c, err := r.Cookie("sid"); err == nil {
		id = c.Value
	} else {
		s.mu.Lock()
		s.next++
		id = strconv.Itoa(s.next)
		s.mu.Unlock()
	}
	s.mu.Lock()
	s.sessions[id] = email
	s.mu.Unlock()
	http.SetCookie(w, &http.Cookie{Name: "sid", Value: id}) // no HttpOnly, Secure, SameSite
	w.Write([]byte("welcome"))
}

// Logout clears the cookie; the server-side session stays valid forever.
func (s *Server) Logout(w http.ResponseWriter, r *http.Request) {
	http.SetCookie(w, &http.Cookie{Name: "sid", Value: "", MaxAge: -1})
}

func (s *Server) Me(w http.ResponseWriter, r *http.Request) {
	c, err := r.Cookie("sid")
	s.mu.Lock()
	email, ok := "", false
	if err == nil {
		email, ok = s.sessions[c.Value]
	}
	s.mu.Unlock()
	if !ok {
		http.Error(w, "unauthenticated", http.StatusUnauthorized)
		return
	}
	w.Write([]byte(email))
}

Its test is a list of findings: each assertion proves one weakness.

go
package before

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strconv"
	"strings"
	"testing"
)

func login(s *Server, email, pw string, cookie *http.Cookie) *httptest.ResponseRecorder {
	form := url.Values{"email": {email}, "password": {pw}}
	req := httptest.NewRequest("POST", "/login", strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	if cookie != nil {
		req.AddCookie(cookie)
	}
	rec := httptest.NewRecorder()
	s.Login(rec, req)
	return rec
}

// Each assertion documents a weakness; package after fixes every one.
func TestBeforeWeaknesses(t *testing.T) {
	s := New()
	a := s.Register("alice@example.test", "summer2026")
	b := s.Register("bob@example.test", "summer2026")
	if a != b {
		t.Fatal("expected identical hashes for identical passwords (no salt)")
	}

	unknown := login(s, "nobody@example.test", "x", nil)
	wrong := login(s, "alice@example.test", "x", nil)
	if unknown.Code == wrong.Code || unknown.Body.String() == wrong.Body.String() {
		t.Fatal("expected distinguishable answers (user enumeration)")
	}

	ok := login(s, "alice@example.test", "summer2026", nil)
	c := ok.Result().Cookies()[0]
	if raw := ok.Header().Get("Set-Cookie"); raw != "sid="+c.Value {
		t.Fatalf("expected a cookie without flags, got %q", raw)
	}
	n, err := strconv.Atoi(c.Value)
	if err != nil {
		t.Fatal("expected a numeric session id")
	}
	if next := strconv.Itoa(n + 1); next != "1002" {
		t.Fatalf("expected the next id to be guessable, got %s", next)
	}

	// Session fixation: the attacker's planted id becomes an authenticated one.
	planted := &http.Cookie{Name: "sid", Value: "attacker-chosen"}
	login(s, "bob@example.test", "summer2026", planted)
	req := httptest.NewRequest("GET", "/me", nil)
	req.AddCookie(planted)
	rec := httptest.NewRecorder()
	s.Me(rec, req)
	if rec.Body.String() != "bob@example.test" {
		t.Fatal("expected the planted session id to be logged in as bob")
	}

	// Logout does not end the server-side session.
	s.Logout(httptest.NewRecorder(), req)
	rec = httptest.NewRecorder()
	s.Me(rec, req)
	if rec.Code != 200 {
		t.Fatal("expected the session to survive logout")
	}
}

After ​

The same three endpoints composed from this chapter's packages: Argon2id in PHC format, one generic failure answer computed at the same cost for unknown users, per-account and per-IP throttling with 429 and Retry-After, session rotation on login, a __Host-sid cookie with HttpOnly; Secure; SameSite=Lax, an upgrade of the stored hash when the cost policy changed, and a logout that deletes the server-side session. Routes deliberately mounts no CSRF layer so the tests stay about authentication; Secure (in Lab 6) is the same server with the CSRF layer and a token endpoint, as in the pipeline.

go
// Package after is the same login done right, composed from this module's
// packages: Argon2id in PHC format, constant-time compare, a dummy hash for
// unknown users, one generic error, per-account and per-IP throttling,
// session rotation on login, a __Host- cookie with all flags, rehash on
// login, and a logout that ends the session on the server.
package after

import (
	"net/http"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"

	"academy/authentication-in-go/lockout"
	"academy/authentication-in-go/password"
	"academy/authentication-in-go/session"
)

type User struct {
	ID    int64
	Email string
	Hash  string // $argon2id$v=19$...
}

type Server struct {
	Params   password.Params
	Sessions *session.Store
	Guard    *lockout.Guard

	mu      sync.Mutex
	byEmail map[string]*User
	dummy   string       // hash of a random password, same params as real ones
	Hashes  atomic.Int64 // number of Argon2id computations, for the test
}

func New(p password.Params, s *session.Store, g *lockout.Guard) *Server {
	dummy, _ := password.Hash(session.NewID(), p)
	return &Server{Params: p, Sessions: s, Guard: g, byEmail: map[string]*User{}, dummy: dummy}
}

func normEmail(e string) string { return strings.ToLower(strings.TrimSpace(e)) }

func (s *Server) Register(id int64, email, plain string) error {
	h, err := password.Hash(plain, s.Params)
	if err != nil {
		return err
	}
	s.mu.Lock()
	s.byEmail[normEmail(email)] = &User{ID: id, Email: normEmail(email), Hash: h}
	s.mu.Unlock()
	return nil
}

// generic is the single failure message, for unknown e-mail and wrong password.
const generic = "invalid email or password"

func clientIP(r *http.Request) string {
	host := r.RemoteAddr // behind a proxy, use the trusted real-IP middleware's value
	if i := strings.LastIndexByte(host, ':'); i > 0 {
		host = host[:i]
	}
	return host
}

func (s *Server) Login(w http.ResponseWriter, r *http.Request) {
	email := normEmail(r.PostFormValue("email"))
	plain := r.PostFormValue("password")
	if len(plain) > 1024 { // bound the hashing work an attacker can request
		http.Error(w, generic, http.StatusUnauthorized)
		return
	}
	if wait := s.Guard.Allow(email, clientIP(r)); wait > 0 {
		w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds()+0.999)))
		http.Error(w, "too many attempts, try again later", http.StatusTooManyRequests)
		return
	}

	// Copy what we need under the lock: a concurrent login may be rewriting
	// u.Hash (rehash on login) at the same moment.
	s.mu.Lock()
	u := s.byEmail[email]
	encoded, userID := s.dummy, int64(0)
	if u != nil {
		encoded, userID = u.Hash, u.ID
	}
	s.mu.Unlock()
	ok, rehash, err := password.Verify(plain, encoded, s.Params) // same cost either way
	s.Hashes.Add(1)
	if err != nil || !ok || u == nil {
		s.Guard.Fail(email)
		http.Error(w, generic, http.StatusUnauthorized)
		return
	}
	s.Guard.Succeed(email)
	if rehash { // parameters were raised since this hash was made
		if h, err := password.Hash(plain, s.Params); err == nil {
			s.mu.Lock()
			if u.Hash == encoded { // nobody upgraded it meanwhile
				u.Hash = h
			}
			s.mu.Unlock()
		}
	}

	// Rotation on login: whatever ID the browser had is dropped.
	old := ""
	if c, err := r.Cookie(session.CookieName); err == nil {
		old = c.Value
	}
	id := s.Sessions.Rotate(old, userID)
	http.SetCookie(w, session.Cookie(id))
	w.Header().Set("Cache-Control", "no-store")
	w.WriteHeader(http.StatusNoContent)
}

// Logout deletes the server-side session and the cookie. It is POST only;
// in a real stack it sits behind csrf.Protector (and CrossOriginProtection)
// so another site cannot log the user out. Routes leaves CSRF out to keep
// these tests about authentication; the csrf package tests that layer.
func (s *Server) Logout(w http.ResponseWriter, r *http.Request) {
	if c, err := r.Cookie(session.CookieName); err == nil {
		s.Sessions.Destroy(c.Value)
	}
	http.SetCookie(w, session.ClearCookie())
	w.Header().Set("Clear-Site-Data", `"cache", "cookies", "storage"`)
	w.WriteHeader(http.StatusNoContent)
}

func (s *Server) Me(w http.ResponseWriter, r *http.Request) {
	sess, ok := session.From(r.Context())
	if !ok || sess.UserID == 0 {
		http.Error(w, "authentication required", http.StatusUnauthorized)
		return
	}
	w.Write([]byte(strconv.FormatInt(sess.UserID, 10)))
}

// Routes wires the handlers; session.Load runs on every request.
func (s *Server) Routes() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /login", s.Login)
	mux.HandleFunc("POST /logout", s.Logout)
	mux.HandleFunc("GET /me", s.Me)
	return s.Sessions.Load(mux)
}

The test asserts the security properties, not only the happy path: identical responses and identical hash counts for "no such user" and "wrong password", a planted pre-login session ID that stops working, exact cookie attributes, rehash on login, and throttling.

go
package after

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
	"time"

	"academy/authentication-in-go/lockout"
	"academy/authentication-in-go/password"
	"academy/authentication-in-go/session"
)

var fast = password.Params{Memory: 1024, Time: 1, Threads: 1, SaltLen: 16, KeyLen: 32}

func newServer(t *testing.T) (*Server, http.Handler) {
	t.Helper()
	s := New(fast, session.NewStore(30*time.Minute, 12*time.Hour), lockout.New())
	if err := s.Register(7, "alice@example.test", "correct horse battery staple"); err != nil {
		t.Fatal(err)
	}
	return s, s.Routes()
}

func post(h http.Handler, path, email, pw, ip string, c *http.Cookie) *httptest.ResponseRecorder {
	form := url.Values{"email": {email}, "password": {pw}}
	req := httptest.NewRequest("POST", path, strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.RemoteAddr = ip + ":51000"
	if c != nil {
		req.AddCookie(c)
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec
}

func me(h http.Handler, c *http.Cookie) int {
	req := httptest.NewRequest("GET", "/me", nil)
	if c != nil {
		req.AddCookie(&http.Cookie{Name: c.Name, Value: c.Value})
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec.Code
}

func TestUnknownUserAndWrongPasswordLookTheSame(t *testing.T) {
	s, h := newServer(t)
	a := post(h, "/login", "nobody@example.test", "whatever", "192.0.2.1", nil)
	b := post(h, "/login", "alice@example.test", "wrong password", "192.0.2.1", nil)
	if a.Code != b.Code || a.Body.String() != b.Body.String() {
		t.Fatalf("distinguishable: %d %q vs %d %q", a.Code, a.Body, b.Code, b.Body)
	}
	if a.Code != http.StatusUnauthorized {
		t.Fatalf("code %d", a.Code)
	}
	if got := s.Hashes.Load(); got != 2 {
		t.Fatalf("%d hash computations, want 2 (dummy hash for the unknown user)", got)
	}
}

func TestLoginRotatesAndSetsFlags(t *testing.T) {
	s, h := newServer(t)
	planted := &http.Cookie{Name: session.CookieName, Value: s.Sessions.Create(0)}
	rec := post(h, "/login", "Alice@Example.test", "correct horse battery staple", "192.0.2.1", planted)
	if rec.Code != http.StatusNoContent {
		t.Fatalf("login %d %s", rec.Code, rec.Body)
	}
	raw := rec.Header().Get("Set-Cookie")
	if !strings.HasPrefix(raw, "__Host-sid=") || !strings.HasSuffix(raw, "; Path=/; HttpOnly; Secure; SameSite=Lax") {
		t.Fatalf("Set-Cookie %q", raw)
	}
	c := rec.Result().Cookies()[0]
	if c.Value == planted.Value {
		t.Fatal("session id not rotated")
	}
	if me(h, planted) != http.StatusUnauthorized {
		t.Fatal("planted pre-login id still works: fixation")
	}
	if me(h, c) != http.StatusOK {
		t.Fatal("new session rejected")
	}

	out := post(h, "/logout", "", "", "192.0.2.1", c)
	if !strings.Contains(out.Header().Get("Set-Cookie"), "Max-Age=0") {
		t.Fatalf("logout cookie %q", out.Header().Get("Set-Cookie"))
	}
	if me(h, c) != http.StatusUnauthorized {
		t.Fatal("session alive on the server after logout")
	}
}

func TestRehashOnLogin(t *testing.T) {
	s, h := newServer(t)
	before := s.byEmail["alice@example.test"].Hash
	s.Params.Time = 2 // policy raised the cost
	post(h, "/login", "alice@example.test", "correct horse battery staple", "192.0.2.1", nil)
	after := s.byEmail["alice@example.test"].Hash
	if after == before || !strings.Contains(after, ",t=2,") {
		t.Fatalf("hash not upgraded: %s", after)
	}
}

func TestThrottleReturns429(t *testing.T) {
	_, h := newServer(t)
	for range 6 {
		post(h, "/login", "alice@example.test", "guess", "192.0.2.1", nil)
	}
	rec := post(h, "/login", "alice@example.test", "correct horse battery staple", "198.51.100.9", nil)
	if rec.Code != http.StatusTooManyRequests || rec.Header().Get("Retry-After") == "" {
		t.Fatalf("code %d Retry-After %q", rec.Code, rec.Header().Get("Retry-After"))
	}
}

Logins can upgrade the stored hash while other logins read it, so the handler copies u.Hash and u.ID under the lock and writes the new hash only if nobody upgraded it meanwhile; the concurrent test runs 20 rounds of 8 simultaneous logins under -race.

go
package after

import (
	"fmt"
	"net/http"
	"sync"
	"testing"

	"academy/authentication-in-go/password"
)

// Concurrent successful logins while the stored hash is below policy: one
// of them rehashes and writes User.Hash while the others read it. Each
// round resets the hash to the old parameters. Run with -race.
func TestConcurrentLoginsDuringRehash(t *testing.T) {
	s, h := newServer(t)
	old, _ := password.Hash("correct horse battery staple", fast)
	s.Params.Time = 2
	for round := range 20 {
		s.mu.Lock()
		s.byEmail["alice@example.test"].Hash = old
		s.mu.Unlock()
		var wg sync.WaitGroup
		for i := range 8 {
			wg.Add(1)
			go func() {
				defer wg.Done()
				ip := fmt.Sprintf("198.51.%d.%d", round, i)
				if rec := post(h, "/login", "alice@example.test", "correct horse battery staple", ip, nil); rec.Code != http.StatusNoContent {
					t.Errorf("round %d login %d: %d", round, i, rec.Code)
				}
			}()
		}
		wg.Wait()
	}
}

The Go angle ​

Go gives you the primitives and leaves the framework to you. The standard library has everything for the session path (crypto/rand, crypto/sha256, crypto/subtle, crypto/hmac, net/http cookies, context, html/template, and since Go 1.25 http.CrossOriginProtection); password hashing lives in golang.org/x/crypto, maintained by the Go team but versioned separately. Everything else is a small, focused package: alexedwards/scs/v2 and gorilla/sessions for sessions, golang-jwt/jwt/v5 for JWT, MicahParks/keyfunc for JWKS, golang.org/x/oauth2 and coreos/go-oidc/v3 for OAuth and OpenID Connect, pquerna/otp for TOTP, go-webauthn/webauthn for passkeys, microcosm-cc/bluemonday for HTML sanitizing. There is no Go equivalent of Laravel's starter kits that wires them together, which is a cost (you write the login flow) and a benefit (you can read and test every line of it, as this module does).

The concept catalogue ​

Password hashing: slow, salted, optionally peppered Must-know ​

In plain words: You never store the password. You store the result of a function that is cheap to run once at login and ruinously expensive to run a billion times, with a random salt mixed in so that two users with the same password get different results and no precomputed table helps.

Common misunderstanding: "Encrypting passwords is safer than hashing them, because we can recover them if needed." Anything you can decrypt, an attacker who gets the key can decrypt. OWASP: passwords "should be securely hashed using modern, adaptive hashing algorithms (e.g., Argon2id, bcrypt, or PBKDF2), rather than encrypted or stored in plaintext." A second one: "a salt must be secret." It is stored next to the hash; its job is uniqueness, not secrecy. The secret ingredient is the pepper.

Definition: a password hashing scheme takes a password, a salt and a cost and produces a hash. NIST SP 800-63B-4: "Passwords SHALL be salted and hashed using a suitable password hashing scheme" and "The salt SHALL be at least 32 bits in length and chosen to minimize salt value collisions among stored hashes". OWASP's ranking: Argon2id first, scrypt if Argon2id is unavailable, bcrypt "only ... in legacy systems where Argon2 and scrypt are not available", PBKDF2 with 600,000 iterations of HMAC-SHA-256 where FIPS-140 compliance is required. Salts are per-password random values stored in the hash string. Peppers are one shared secret, kept outside the database ("in 'secrets vaults' or HSMs"), applied either before hashing (pre-hashing pepper) or as an HMAC over the hash (post-hashing pepper). A pepper protects against a database-only leak (SQL injection, a stolen backup); its cost is that "changing a pepper will require forcing all users whose passwords were protected by the previous pepper to reset their passwords".

attacker with a stolen users table, one RTX-class GPU (orders of magnitude, not a benchmark)
1  sha256(pw), no salt     one hash per candidate covers ALL users; rainbow tables work
2  sha256(salt || pw)      one hash per candidate PER user; still ~10^9 guesses/s
3  bcrypt cost 12          ~175 ms per guess on one CPU core here: ~6 guesses/s/core
4  argon2id m=19MiB t=2    ~15 ms and 19 MiB per guess: memory, not cores, is the limit
5  + pepper in a vault     table alone is useless: the attacker also needs the vault

Real scenario: a SQL injection that dumps users; a database backup left in a public bucket; a log line that printed a request body with password=... (hashing does not help there: never log the form); a migration from a legacy MD5 schema; two employees with the same password Summer2026! whose hashes must not reveal that.

SchemeGo packageMemory-hardInput limitOWASP position
Argon2idgolang.org/x/crypto/argon2 (IDKey)YesNone in practiceFirst choice
scryptgolang.org/x/crypto/scryptYesNoneIf Argon2id is unavailable
bcryptgolang.org/x/crypto/bcryptNo (Blowfish state: p [18]uint32 + four [256]uint32 S-boxes, about 4 KiB)72 bytesLegacy systems
PBKDF2crypto/pbkdf2 (Go 1.24) / x/crypto/pbkdf2NoNoneFIPS-140 requirement, 600,000+ iterations
SHA-256, MD5, SHA-1crypto/sha256 etc.NoNoneNever for passwords

Fix / how to use it: pick Argon2id for new systems, keep the parameters in the stored string so they can change, salt with 16 random bytes, and add a pepper only if you can actually keep it out of the database and rotate it. The primitives themselves (SHA-2, HMAC, crypto/rand) are walked through in Hashing & Crypto.

Argon2id with x/crypto/argon2 and the PHC string format Must-know ​

In plain words: Argon2id fills a block of memory with pseudo-random data derived from the password and salt, then reads it back in a password-dependent order. An attacker cannot trade memory for speed, so a GPU with thousands of cores but little memory per core loses its advantage.

Common misunderstanding: "More threads (p) make it harder to crack." OWASP: parallelism "controls the number of lanes over which the memory is divided; increasing p does not multiply the total memory or act as an iteration count." Another one: "copy the 2 GiB example from the RFC." RFC 9106's FIRST RECOMMENDED option (t=1, p=4, m=2 GiB) is sized for a machine that does little else; on a login server that handles 50 logins at once it is 100 GiB of RAM. Size m for concurrency.

Definition: argon2.IDKey(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte (memory in KiB). RFC 9106 section 4: "If much less memory is available, a uniformly safe option is Argon2id with t=3 iterations, p=4 lanes, m=2^(16) (64 MiB of RAM), 128-bit salt, and 256-bit tag size. This is the SECOND RECOMMENDED option." OWASP's minimum list trades memory for passes at equal strength: m=47104 t=1, m=19456 t=2, m=12288 t=3, m=9216 t=4, m=7168 t=5, all p=1. The output is stored in the PHC string format, which C2SP defines as $<id>[$v=<version>][$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]], with salt and hash in standard base64 without padding. The x/crypto doc comment changed between versions: v0.48.0 (pinned here) cites "RFC 9106 Section 7.3" and calls time=1, memory=64*1024 "a sensible number"; the current master cites section 4's two recommended options. The parameters are the same family; the module compiles against v0.48.0.

Hash("correct horse battery staple", OWASP)   (real output of this module)
1  salt   = 16 bytes from crypto/rand
2  key    = argon2.IDKey(pw, salt, t=2, m=19456, p=1, 32)
3  store  $argon2id$v=19$m=19456,t=2,p=1$P+oy00nASCUPp2mqAQNbNA$Cnca6pEujpk8B7AfAh9cB1VfEaQ0sJzEJhGJS++iYzA
Verify(pw, stored, OWASP)
4  parse  v=19 (argon2.Version = 0x13), m, t, p, salt, key
5  other  = argon2.IDKey(pw, salt, t, m, p, len(key))     parameters from the STRING, not from config
6  subtle.ConstantTimeCompare(key, other) == 1 ?
7  stored params != OWASP ? -> needsRehash = true
One stored string carries everything needed to verify it$argon2id$v=19$m=19456,t=2,p=1$P+oy00nASCUPp2mq…$Cnca6pEujpk8B7Af…algorithmversion 0x13KiB, passes, lanes16-byte salt, base6432-byte tag, base64POST /loginthrottle check first (429)look up user by emailmissing: use the dummy hashargon2.IDKey(pw, salt, t, m, p)same cost on both pathssubtle.ConstantTimeCompareand the user really existsno401 "invalid email or password"count a failure for this emailyesstored params != current?rehash now, while plaintext is knownrotate session IDSet-Cookie: __Host-sid=…No pepper or secret appears in the string: a pepper lives in a secret store and is applied before hashing.Params in the string let old and new hashes coexist; Verify reads them, needsRehash compares them with policy.

Real scenario: a SaaS login API sized for 200 logins per second per instance; a mobile backend whose containers have 512 MiB of RAM (m=19 MiB, t=2 fits; 64 MiB at 50 concurrent logins does not); a migration that raises t from 2 to 3 and upgrades hashes as users log in; a KDF for an encrypted export (that is key derivation, also IDKey, but with its own salt and no PHC string).

ProfilemtpTime per hash hereMemory per hash
OWASP minimum (password.OWASP)19456 KiB2115.5 ms19.9 MB
RFC 9106 second option (password.RFC9106Second)65536 KiB3426.9 ms67.1 MB
RFC 9106 first option2097152 KiB14not run (2 GiB)2 GiB
Laravel argon2id driver, docs examplememory 1024time 2threads 2PHP side, not measuredper Hash::make options

Fix / how to use it: the password package hashes, verifies, reports needsRehash, and rejects malformed or wrong-version strings. Tests run with tiny parameters (1 MiB) so -race stays fast, plus one test at the real OWASP parameters.

go
// Package password stores and verifies passwords: Argon2id in the PHC string
// format, a bcrypt fallback, an optional pepper, and a NIST SP 800-63B-4
// style policy.
package password

import (
	"crypto/rand"
	"crypto/subtle"
	"encoding/base64"
	"errors"
	"fmt"
	"strings"

	"golang.org/x/crypto/argon2"
)

// Params are the Argon2id cost parameters. Memory is in KiB.
type Params struct {
	Memory  uint32 // m, KiB
	Time    uint32 // t, passes over memory
	Threads uint8  // p, lanes
	SaltLen uint32 // bytes
	KeyLen  uint32 // bytes (the "tag")
}

// OWASP is the OWASP Password Storage Cheat Sheet minimum m=19456 (19 MiB),
// t=2, p=1, with a 128-bit salt and a 256-bit tag as in RFC 9106.
var OWASP = Params{Memory: 19 * 1024, Time: 2, Threads: 1, SaltLen: 16, KeyLen: 32}

// RFC9106Second is the RFC 9106 "SECOND RECOMMENDED option":
// t=3, p=4, m=2^16 KiB (64 MiB).
var RFC9106Second = Params{Memory: 64 * 1024, Time: 3, Threads: 4, SaltLen: 16, KeyLen: 32}

var (
	ErrInvalidHash         = errors.New("password: hash is not in the expected PHC format")
	ErrIncompatibleVersion = errors.New("password: incompatible argon2 version")
)

// Hash returns a PHC string such as
// $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash> (unpadded standard base64).
func Hash(plain string, p Params) (string, error) {
	salt := make([]byte, p.SaltLen)
	if _, err := rand.Read(salt); err != nil { // never fails since Go 1.24
		return "", err
	}
	key := argon2.IDKey([]byte(plain), salt, p.Time, p.Memory, p.Threads, p.KeyLen)
	b64 := base64.RawStdEncoding
	return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
		argon2.Version, p.Memory, p.Time, p.Threads,
		b64.EncodeToString(salt), b64.EncodeToString(key)), nil
}

// Verify recomputes the hash with the parameters stored in encoded and
// compares in constant time. needsRehash is true when the stored parameters
// are weaker than (or just different from) want, so the caller can upgrade
// the hash right after a successful login, while it still has the plaintext.
func Verify(plain, encoded string, want Params) (ok, needsRehash bool, err error) {
	p, salt, key, err := decode(encoded)
	if err != nil {
		return false, false, err
	}
	other := argon2.IDKey([]byte(plain), salt, p.Time, p.Memory, p.Threads, uint32(len(key)))
	if subtle.ConstantTimeCompare(key, other) != 1 {
		return false, false, nil
	}
	needsRehash = p.Memory != want.Memory || p.Time != want.Time ||
		p.Threads != want.Threads || uint32(len(key)) != want.KeyLen ||
		uint32(len(salt)) != want.SaltLen
	return true, needsRehash, nil
}

func decode(encoded string) (p Params, salt, key []byte, err error) {
	// "", "argon2id", "v=19", "m=..,t=..,p=..", salt, hash
	parts := strings.Split(encoded, "$")
	if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
		return p, nil, nil, ErrInvalidHash
	}
	var version int
	if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
		return p, nil, nil, ErrInvalidHash
	}
	if version != argon2.Version {
		return p, nil, nil, ErrIncompatibleVersion
	}
	if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Time, &p.Threads); err != nil {
		return p, nil, nil, ErrInvalidHash
	}
	b64 := base64.RawStdEncoding
	if salt, err = b64.DecodeString(parts[4]); err != nil {
		return p, nil, nil, ErrInvalidHash
	}
	if key, err = b64.DecodeString(parts[5]); err != nil {
		return p, nil, nil, ErrInvalidHash
	}
	if p.Memory == 0 || p.Time == 0 || p.Threads == 0 || len(key) < 16 {
		return p, nil, nil, ErrInvalidHash
	}
	p.SaltLen, p.KeyLen = uint32(len(salt)), uint32(len(key))
	return p, salt, key, nil
}

bcrypt with x/crypto/bcrypt: cost and the 72-byte limit Must-know ​

In plain words: bcrypt is the older adaptive hash: a cost number decides how many rounds of an expensive key setup run, and each +1 doubles the time. It is still fine for existing systems; it is not memory-hard.

Common misunderstanding: "bcrypt hashes the whole password." Classic implementations silently used only the first 72 bytes, so two long passphrases with the same first 72 bytes matched. x/crypto/bcrypt refuses instead: "GenerateFromPassword does not accept passwords longer than 72 bytes", returning bcrypt: password length exceeds 72 bytes (bcrypt.ErrPasswordTooLong). Note bytes, not characters: 25 emoji are 100 bytes. Another one: "cost 4 is fine in production because tests pass." bcrypt.MinCost is 4 and exists for tests.

Definition: bcrypt.GenerateFromPassword(password []byte, cost int); "If the cost given is less than MinCost, the cost will be set to DefaultCost" (10); MaxCost is 31; out-of-range costs give crypto/bcrypt: cost %d is outside allowed inclusive range 4..31. CompareHashAndPassword returns nil or bcrypt.ErrMismatchedHashAndPassword; bcrypt.Cost(hash) reads the stored cost so you can decide to rehash. The string looks like $2a$12$<22 chars salt><31 chars hash>, in bcrypt's own base64 alphabet, not PHC. OWASP: "The work factor should be as large as verification server performance will allow, with a minimum of 10." If you must accept longer inputs, OWASP gives one safe pre-hash: bcrypt(base64(hmac-sha384(data:$password, key:$pepper)), $salt, $cost), because a raw digest can contain NUL bytes and a plain unkeyed pre-hash enables "password shucking".

cost   rounds 2^cost   time per hash on this machine
10     1024            ~44 ms   (DefaultCost; extrapolated: cost 12 / 4)
12     4096            176 ms   (measured, BenchmarkBcryptCost12)
14     16384           ~0.7 s   (too slow for an interactive login)

Real scenario: a Laravel app moving to Go that already has $2y$12$... hashes in users.password (x/crypto reads $2y$); a service that accepted 100-character passphrases and now gets ErrPasswordTooLong; a cost raised from 10 to 12 with rehash on login; a FIPS deployment that must use PBKDF2 instead.

SituationDo
New systemArgon2id, not bcrypt
Existing bcrypt hashesKeep verifying; rehash to Argon2id on next successful login
Password > 72 bytesReject (policy max) or pepper + HMAC-SHA-384 + base64 pre-hash
Cost below current policybcrypt.Cost < target → rehash after successful login
Tests too slowUse bcrypt.MinCost in tests only

Fix / how to use it: the bcrypt wrapper refuses long input and reports needsRehash; Peppered is the OWASP pre-hash, 64 base64 characters, inside bcrypt's limit.

go
package password

import (
	"errors"

	"golang.org/x/crypto/bcrypt"
)

// BcryptCost is above bcrypt.DefaultCost (10), the OWASP minimum, and equal
// to the rounds value used in Laravel's hashing docs.
const BcryptCost = 12

// HashBcrypt refuses passwords longer than 72 bytes instead of silently
// truncating them; x/crypto returns bcrypt.ErrPasswordTooLong for those.
func HashBcrypt(plain string) (string, error) {
	h, err := bcrypt.GenerateFromPassword([]byte(plain), BcryptCost)
	if err != nil {
		return "", err
	}
	return string(h), nil
}

// VerifyBcrypt reports a match and whether the stored cost is below the
// current one. A mismatch is not an error.
func VerifyBcrypt(plain, hashed string) (ok, needsRehash bool, err error) {
	err = bcrypt.CompareHashAndPassword([]byte(hashed), []byte(plain))
	if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
		return false, false, nil
	}
	if err != nil {
		return false, false, err
	}
	cost, err := bcrypt.Cost([]byte(hashed))
	if err != nil {
		return false, false, err
	}
	return true, cost < BcryptCost, nil
}
go
package password

import (
	"crypto/hmac"
	"crypto/sha512"
	"encoding/base64"
)

// Peppered returns base64(HMAC-SHA-384(pepper, plain)), the pre-hash OWASP
// gives for bcrypt: base64 avoids NUL bytes, and 64 base64 characters fit in
// bcrypt's 72-byte limit. The pepper lives in a secret store, never in the
// database next to the hashes. Feed the result to Hash or HashBcrypt.
func Peppered(plain string, pepper []byte) string {
	m := hmac.New(sha512.New384, pepper)
	m.Write([]byte(plain))
	return base64.StdEncoding.EncodeToString(m.Sum(nil))
}

Constant-time compare and timing attacks Must-know ​

In plain words: If your code answers faster when the guess is "more wrong", the stopwatch tells the attacker something. Compare secrets with a function whose running time does not depend on where the first difference is, and make the "no such user" path cost the same as the "wrong password" path.

Common misunderstanding: "Comparing hashes with == is safe because the attacker does not control the hash." For password hashes that is mostly true (the attacker cannot steer the Argon2 output byte by byte), but the same code is then copied to compare API keys, HMAC signatures, CSRF tokens and reset tokens, where it is not. The bigger, more practical timing leak is the "quick exit": returning before hashing when the user does not exist. OWASP shows exactly that: "if the user doesn't exist, the application will directly throw an error. Otherwise, when the user exists and the password doesn't, it is apparent that there will be more processing".

Definition: subtle.ConstantTimeCompare(x, y []byte) int "returns 1 if the two slices, x and y, have equal contents and 0 otherwise. The time taken is a function of the length of the slices and is independent of the contents. If the lengths of x and y do not match it returns 0 immediately." hmac.Equal wraps it for MACs. A timing attack measures response times over many requests to learn a secret or a fact (which accounts exist). The fix for the user-lookup leak is a dummy hash: compute the same Argon2id with the same parameters against a fixed hash when the user is missing, then fail with the same message.

     quick exit (before)                      dummy hash (after)
1    lookup alice: found  -> hash ~15 ms      lookup alice: found  -> hash ~15 ms
2    lookup nobody: missing -> 404 in 0.1 ms  lookup nobody: missing -> hash dummy ~15 ms
3    attacker: 0.1 ms means "no account"      attacker: same time, same 401, same body
4    enumerates the customer list             learns nothing; throttling limits the rest

Real scenario: a B2B app where knowing that cfo@victim.example has an account is the first step of a phishing campaign; an API key check if key == cfg.Key; a webhook signature check with bytes.Equal; a password reset endpoint that answers "email sent" in 900 ms (SMTP) vs "unknown" in 5 ms.

ComparisonConstant time?Use for
a == b on strings, bytes.EqualNo: stops at the first differenceNon-secret data
subtle.ConstantTimeCompareYes for equal lengths; length leaksTokens, keys, hash outputs
hmac.EqualYes (same function)MACs, signed cookies, CSRF tokens
bcrypt.CompareHashAndPasswordUses subtle internallybcrypt hashes
Lookup by sha256(token) in a map or indexThe lookup key is a hash of the secret, not the secretReset, refresh, session tokens

Fix / how to use it: password.Verify ends in subtle.ConstantTimeCompare; after.Login hashes a dummy for unknown users and the test asserts two hash computations for two failed logins. The general HMAC and constant-time API is in Hashing & Crypto.

Password policy: NIST SP 800-63B-4 Important ​

In plain words: Long beats complicated. Require length, check the password against a list of common and breached passwords, allow anything printable (including spaces and emoji), and stop forcing people to change passwords every 90 days.

Common misunderstanding: "One uppercase, one digit, one symbol makes passwords strong." NIST: "Verifiers and CSPs SHALL NOT impose other composition rules (e.g., requiring mixtures of different character types) for passwords", because users answer password with Password1!. Another one: "a maximum of 16 characters is reasonable." NIST says "Verifiers and CSPs SHOULD permit a maximum password length of at least 64 characters." Set a high maximum only to bound hashing work.

Definition: NIST SP 800-63B-4 section 3.1.1.2 (2025): "Verifiers and CSPs SHALL require passwords that are used as a single-factor authentication mechanism to be a minimum of 15 characters in length. Verifiers and CSPs MAY allow passwords that are only used as part of multi-factor authentication processes to be shorter but SHALL require them to be a minimum of eight characters in length." Prospective passwords SHALL be compared "against a blocklist that contains known commonly used, expected, or compromised passwords", and "Verifiers and CSPs SHALL NOT require subscribers to change passwords periodically. However, verifiers SHALL force a change if there is evidence that the authenticator has been compromised." Length is counted in characters: "Each Unicode code point SHALL be counted as a single character when evaluating password length", and verifiers SHOULD apply NFC normalization before hashing, which in Go needs golang.org/x/text/unicode/norm (not used in this module).

Policy{MinRunes: 15, MaxRunes: 128, Blocklist: {...}}.Check(...)   (package password tests)
1  "Tr0ub4dor&3"                     -> too short (11): symbols do not help
2  "correct horse battery staple"    -> ok: long, lowercase, spaces
3  "PasswordPassword"                -> blocklisted (case-insensitive)
4  15 x "ŝ" (30 bytes)                -> ok: counts runes, not bytes
5  129 x "a"                          -> too long: bounds hashing work

Real scenario: a sign-up form that rejected passphrases with spaces; an admin console with a 90-day rotation rule that produced Winter2026!, Spring2026!; a breached-password check against the top 100,000 list at registration and at every password change; a 15-character minimum for a consumer app without MFA and 8 for staff who must use TOTP.

RuleNIST SP 800-63B-4Common legacy rule
Minimum length15 (single-factor), 8 (part of MFA)8
Maximum lengthPermit at least 6416 or 20
Composition (upper/digit/symbol)SHALL NOT imposeRequired
Periodic changeSHALL NOT require; force on compromiseEvery 90 days
Blocklist of common/breachedSHALL checkRare
Hints, security questionsSHALL NOT prompt for knowledge-based authenticationCommon
Throttling≤ 100 consecutive failures per accountOften none

Fix / how to use it: the Policy type in the password package is ten lines because the rules are simple; the blocklist is the part that needs maintenance.

go
package password

import (
	"errors"
	"strings"
	"unicode/utf8"
)

var (
	ErrTooShort    = errors.New("password: too short")
	ErrTooLong     = errors.New("password: too long")
	ErrBlocklisted = errors.New("password: appears in a list of common or breached passwords")
)

// Policy follows NIST SP 800-63B-4 section 3.1.1.2: a length minimum (15 for
// single-factor, 8 when the password is only one factor of MFA), at least 64
// characters allowed, a blocklist, and no composition rules or forced
// periodic changes.
type Policy struct {
	MinRunes  int                 // 15, or 8 when MFA is enforced
	MaxRunes  int                 // >= 64; caps hashing work per request
	Blocklist map[string]struct{} // lower-cased common/breached passwords
}

// Check counts Unicode characters, not bytes, and deliberately has no
// "one digit, one symbol" rule.
func (p Policy) Check(plain string) error {
	n := utf8.RuneCountInString(plain)
	switch {
	case n < p.MinRunes:
		return ErrTooShort
	case n > p.MaxRunes:
		return ErrTooLong
	}
	if _, bad := p.Blocklist[strings.ToLower(plain)]; bad {
		return ErrBlocklisted
	}
	return nil
}
go
package password

import (
	"errors"
	"strings"
	"testing"

	"golang.org/x/crypto/bcrypt"
)

// fast keeps -race runs quick; one test below uses the real OWASP params.
var fast = Params{Memory: 1024, Time: 1, Threads: 1, SaltLen: 16, KeyLen: 32}

func TestHashVerifyRoundTrip(t *testing.T) {
	h, err := Hash("correct horse battery staple", fast)
	if err != nil {
		t.Fatal(err)
	}
	if !strings.HasPrefix(h, "$argon2id$v=19$m=1024,t=1,p=1$") {
		t.Fatalf("not a PHC string: %s", h)
	}
	ok, rehash, err := Verify("correct horse battery staple", h, fast)
	if err != nil || !ok || rehash {
		t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err)
	}
	ok, _, err = Verify("Correct horse battery staple", h, fast)
	if err != nil || ok {
		t.Fatalf("wrong password accepted: ok=%v err=%v", ok, err)
	}
}

func TestSaltMakesEqualPasswordsDiffer(t *testing.T) {
	a, _ := Hash("same password for two users", fast)
	b, _ := Hash("same password for two users", fast)
	if a == b {
		t.Fatal("two hashes of the same password are equal: salt missing")
	}
}

func TestNeedsRehashWhenParamsChange(t *testing.T) {
	h, _ := Hash("upgrade me on next login", fast)
	stronger := fast
	stronger.Time = 2
	ok, rehash, err := Verify("upgrade me on next login", h, stronger)
	if err != nil || !ok || !rehash {
		t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err)
	}
}

func TestOWASPParams(t *testing.T) {
	h, err := Hash("production parameters once", OWASP)
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(h, "$m=19456,t=2,p=1$") {
		t.Fatalf("unexpected params in %s", h)
	}
	if ok, _, _ := Verify("production parameters once", h, OWASP); !ok {
		t.Fatal("verify failed")
	}
}

func TestDecodeRejectsGarbage(t *testing.T) {
	for _, s := range []string{
		"",
		"plaintext",
		"$argon2i$v=19$m=1024,t=1,p=1$c2FsdA$aGFzaA",
		"$argon2id$v=16$m=1024,t=1,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaA",
		"$argon2id$v=19$m=0,t=1,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaA",
	} {
		if _, _, err := Verify("x", s, fast); err == nil {
			t.Errorf("accepted %q", s)
		}
	}
}

func TestBcryptLimitAndCost(t *testing.T) {
	if _, err := HashBcrypt(strings.Repeat("a", 73)); !errors.Is(err, bcrypt.ErrPasswordTooLong) {
		t.Fatalf("73 bytes: err = %v, want ErrPasswordTooLong", err)
	}
	old, _ := bcrypt.GenerateFromPassword([]byte("legacy password"), bcrypt.MinCost)
	ok, rehash, err := VerifyBcrypt("legacy password", string(old))
	if err != nil || !ok || !rehash {
		t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err)
	}
	ok, _, err = VerifyBcrypt("wrong", string(old))
	if err != nil || ok {
		t.Fatalf("mismatch: ok=%v err=%v", ok, err)
	}
}

func TestPepperFitsBcrypt(t *testing.T) {
	long := strings.Repeat("päss", 40) // 200 bytes
	p := Peppered(long, []byte("pepper-from-a-secret-store-32-by"))
	if len(p) != 64 {
		t.Fatalf("len = %d, want 64", len(p))
	}
	if _, err := HashBcrypt(p); err != nil {
		t.Fatal(err)
	}
	if Peppered(long, []byte("another pepper")) == p {
		t.Fatal("pepper has no effect")
	}
}

func TestPolicy(t *testing.T) {
	p := Policy{MinRunes: 15, MaxRunes: 128, Blocklist: map[string]struct{}{"passwordpassword": {}}}
	cases := map[string]error{
		"Tr0ub4dor&3":                  ErrTooShort, // 11 chars, composition does not help
		"correct horse battery staple": nil,         // long, no digits or symbols: fine
		"PasswordPassword":             ErrBlocklisted,
		"ŝŝŝŝŝŝŝŝŝŝŝŝŝŝŝ":              nil, // 15 runes, 30 bytes
		strings.Repeat("a", 129):       ErrTooLong,
	}
	for in, want := range cases {
		if got := p.Check(in); !errors.Is(got, want) {
			t.Errorf("Check(%q) = %v, want %v", in, got, want)
		}
	}
}

func BenchmarkArgon2idOWASP(b *testing.B) {
	for b.Loop() {
		_, _ = Hash("benchmark password", OWASP)
	}
}

func BenchmarkBcryptCost12(b *testing.B) {
	for b.Loop() {
		_, _ = HashBcrypt("benchmark password")
	}
}

func BenchmarkArgon2idRFC9106Second(b *testing.B) {
	for b.Loop() {
		_, _ = Hash("benchmark password", RFC9106Second)
	}
}

Sessions: server-side store, ID entropy, cookie flags, rotation, timeouts Must-know ​

In plain words: After a successful login the server creates a record ("this is user 7, logged in at 09:00, last seen 09:12") and gives the browser a long random number that points to it. Each request sends the number back in a cookie; the server looks it up. The number is the key to the account, so it must be unguessable, invisible to JavaScript, sent only over HTTPS, replaced at login, and forgotten after inactivity.

Common misunderstanding: "Keeping the same session ID from the anonymous cart into the logged-in state is convenient." It is session fixation: an attacker who planted an ID in the victim's browser (a link, a sibling subdomain, a shared kiosk) is logged in as the victim the moment the victim logs in. OWASP: "The session ID must be renewed or regenerated by the web application after any privilege level change". A second one: "the session ID is random, so storing it as the primary key is fine." Anyone who can read the store (a replica, a backup, a debug dump) can then reuse live sessions; store a hash of it instead.

Definition: a server-side store keeps the session data (Redis, a SQL table, memory for a single instance); the client holds only an identifier. OWASP: "Session identifiers must have at least 64 bits of entropy" and "A strong CSPRNG (Cryptographically Secure Pseudorandom Number Generator) must be used"; this module uses 32 bytes from crypto/rand (256 bits) encoded as base64url. Cookie flags: HttpOnly "Forbids JavaScript from accessing the cookie"; Secure sends it only over https: (except on localhost); SameSite=Lax sends it on top-level navigations with safe methods but not on cross-site POST, fetch or subresources; SameSite=Strict never cross-site; None requires Secure. The __Host- prefix makes the browser reject the cookie unless it has Secure, Path=/ and no Domain, so a subdomain cannot overwrite it ("Recommended for session IDs" per OWASP). Rotation on login issues a new ID and deletes the old record. Timeouts: an idle (inactivity) timeout and an absolute (overall) timeout, both enforced on the server; OWASP: "Common idle timeouts ranges are 2-5 minutes for high-value applications and 15-30 minutes for low risk applications", and for a full office day an absolute timeout "between 4 and 8 hours". NIST SP 800-63B-4 at AAL2: overall reauthentication "no more than 24 hours", inactivity "no more than 1 hour"; at AAL3: 12 hours and 15 minutes.

     browser                          Go server                          store (key = sha256(id))
1    GET /cart (no cookie)  ───────▶  Create(0): id=Ab3..(256 bit) ───▶  9f2c..: {user 0, created 09:00}
2    ◀── Set-Cookie: __Host-sid=Ab3..; Path=/; HttpOnly; Secure; SameSite=Lax
3    POST /login (cookie Ab3..) ───▶  password ok; Rotate(Ab3.., 7) ──▶  delete 9f2c..; 51d0..: {user 7}
4    ◀── Set-Cookie: __Host-sid=Qz8..  (Ab3.. is now worthless: no fixation)
5    GET /orders (Qz8..) 09:40 ─────▶ Get: idle 28 min < 30, age 40 min < 12 h ─▶ LastSeen = 09:40
6    GET /orders (Qz8..) 10:15 ─────▶ Get: idle 35 min > 30 ─▶ delete; 401, redirect to /login
Session: state on the server. JWT: state in the token.Server-side sessionBrowserCookie: __Host-sidGo serversha256(id), timeoutsSession storeRedis / SQL rowuser 7roles, timestamps+ logout, password reset, ban: delete the row, effective on the next request- one store lookup per request; the store must be shared by every instance; CSRF defence neededJWT access tokenClient / SPA / serviceAuthorization: BearerAPI (resource server)alg allow-list, exp/iss/audJWKS cachepublic key by kidAuth serversigns, rotates keysGET /.well-known/jwks.jsonA valid signature stays valid until exp: logout cannot reach a token already handed out+ no lookup per request; any service with the public key can verify; no cookie, so no CSRF for bearer calls- revocation means a 5-15 min access TTL, a jti denylist, and refresh token rotation at the auth server

Real scenario: an online bank with a 5-minute idle timeout and a 4-hour absolute one; a shared library computer where the next person opens the browser an hour later; an e-commerce cart that becomes a logged-in cart at checkout (rotate, but copy the cart); an admin who is granted a role mid-session (rotate); a Redis failover that loses sessions (users log in again, nothing leaks).

PropertyRuleThis modulealexedwards/scs/v2 default
ID entropy≥ 64 bits from a CSPRNG256 bits, crypto/rand256 bits (rand.Read 32 bytes, base64url)
Store holdsA verifier, not the raw IDsha256(id)Raw token unless HashTokenInStore = true
HttpOnlyAlwaysYestrue
SecureAlways (HTTPS)Yesfalse: set it
SameSiteLax (or Strict)LaxLax
Name__Host- prefix__Host-sidsession
RotationOn login, logout, privilege changeStore.RotateRenewToken(ctx)
Idle timeout15-30 min (2-5 high-value)Store.IdleIdleTimeout, 0 = none
Absolute timeout4-12 hStore.AbsoluteLifetime, 24 h
LogoutDelete server-side recordStore.DestroyDestroy(ctx)
All sessions of a userOn password reset, "log out everywhere"Store.DestroyUserIterate the store (Iterate)

Fix / how to use it: the session package is the whole pattern in about 150 lines of standard library; Load is the middleware that attaches the session to the context.

go
// Package session is a server-side session store written with the standard
// library only: 256-bit random IDs from crypto/rand, only a SHA-256 of the
// ID kept in the store, idle and absolute timeouts, rotation on login and
// privilege change, and a __Host- cookie with HttpOnly, Secure and SameSite.
package session

import (
	"context"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"errors"
	"net/http"
	"sync"
	"time"
)

// CookieName uses the __Host- prefix: the browser only accepts it with
// Secure, Path=/ and no Domain, so a sibling subdomain cannot plant it.
const CookieName = "__Host-sid"

var ErrNotFound = errors.New("session: not found or expired")

// Session is the server-side record. The raw ID never appears in it.
type Session struct {
	UserID    int64
	CreatedAt time.Time // start of the absolute timeout
	LastSeen  time.Time // start of the idle timeout
}

// Store is a stand-in for Redis or a SQL table keyed by sha256(ID).
type Store struct {
	mu       sync.Mutex
	byKey    map[string]Session
	Idle     time.Duration // e.g. 30 * time.Minute
	Absolute time.Duration // e.g. 12 * time.Hour
	Now      func() time.Time
}

func NewStore(idle, absolute time.Duration) *Store {
	return &Store{byKey: map[string]Session{}, Idle: idle, Absolute: absolute, Now: time.Now}
}

// NewID returns 32 random bytes as unpadded base64url: 256 bits, four times
// the OWASP minimum of 64 bits of entropy.
func NewID() string {
	b := make([]byte, 32)
	rand.Read(b) // documented never to return an error since Go 1.24
	return base64.RawURLEncoding.EncodeToString(b)
}

// key is what the store sees: a read-only leak of the store (a backup, a
// replica, a debug dump) does not hand out live session IDs.
func key(id string) string {
	sum := sha256.Sum256([]byte(id))
	return hex.EncodeToString(sum[:])
}

// Create starts a session for userID and returns the raw ID for the cookie.
func (s *Store) Create(userID int64) string {
	id := NewID()
	now := s.Now()
	s.mu.Lock()
	s.byKey[key(id)] = Session{UserID: userID, CreatedAt: now, LastSeen: now}
	s.mu.Unlock()
	return id
}

// Get enforces both timeouts and slides the idle one.
func (s *Store) Get(id string) (Session, error) {
	now := s.Now()
	s.mu.Lock()
	defer s.mu.Unlock()
	k := key(id)
	sess, ok := s.byKey[k]
	if !ok {
		return Session{}, ErrNotFound
	}
	if now.Sub(sess.LastSeen) > s.Idle || now.Sub(sess.CreatedAt) > s.Absolute {
		delete(s.byKey, k)
		return Session{}, ErrNotFound
	}
	sess.LastSeen = now
	s.byKey[k] = sess
	return sess, nil
}

// Rotate issues a new ID for the same session data and deletes the old one.
// Call it on login (session fixation), on logout-to-anonymous, on password
// change and on any privilege change.
func (s *Store) Rotate(oldID string, userID int64) string {
	s.mu.Lock()
	delete(s.byKey, key(oldID))
	s.mu.Unlock()
	return s.Create(userID)
}

// Destroy removes one session (logout).
func (s *Store) Destroy(id string) {
	s.mu.Lock()
	delete(s.byKey, key(id))
	s.mu.Unlock()
}

// DestroyUser removes every session of a user (password reset, "log out
// everywhere", account disabled). Returns how many were removed.
func (s *Store) DestroyUser(userID int64) int {
	s.mu.Lock()
	defer s.mu.Unlock()
	n := 0
	for k, v := range s.byKey {
		if v.UserID == userID {
			delete(s.byKey, k)
			n++
		}
	}
	return n
}

// Cookie builds the session cookie. No Expires/MaxAge: a browser-session
// cookie; the server-side timeouts are the real limit.
func Cookie(id string) *http.Cookie {
	return &http.Cookie{
		Name:     CookieName,
		Value:    id,
		Path:     "/",
		HttpOnly: true,                 // no document.cookie access
		Secure:   true,                 // HTTPS only; required by __Host-
		SameSite: http.SameSiteLaxMode, // not sent on cross-site POST
	}
}

// ClearCookie tells the browser to delete the cookie (MaxAge < 0 is
// serialised as Max-Age=0).
func ClearCookie() *http.Cookie {
	c := Cookie("")
	c.MaxAge = -1
	return c
}

type ctxKey struct{}

// Load is middleware: it attaches the session (if any) to the request context.
// It never rejects; RequireUser in package authmw does that.
func (s *Store) Load(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if c, err := r.Cookie(CookieName); err == nil {
			if sess, err := s.Get(c.Value); err == nil {
				r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, sess))
			}
		}
		next.ServeHTTP(w, r)
	})
}

// From returns the session loaded by Load.
func From(ctx context.Context) (Session, bool) {
	sess, ok := ctx.Value(ctxKey{}).(Session)
	return sess, ok
}
go
package session

import (
	"encoding/base64"
	"errors"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

type clock struct{ t time.Time }

func (c *clock) now() time.Time      { return c.t }
func (c *clock) add(d time.Duration) { c.t = c.t.Add(d) }
func newTestStore() (*Store, *clock) {
	c := &clock{t: time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)}
	s := NewStore(30*time.Minute, 12*time.Hour)
	s.Now = c.now
	return s, c
}

func TestIDEntropyAndUniqueness(t *testing.T) {
	seen := map[string]bool{}
	for range 1000 {
		id := NewID()
		raw, err := base64.RawURLEncoding.DecodeString(id)
		if err != nil || len(raw) != 32 {
			t.Fatalf("id %q: %d bytes, err %v", id, len(raw), err)
		}
		if seen[id] {
			t.Fatal("duplicate id")
		}
		seen[id] = true
	}
}

func TestStoreKeepsOnlyHash(t *testing.T) {
	s, _ := newTestStore()
	id := s.Create(7)
	for k := range s.byKey {
		if strings.Contains(k, id) {
			t.Fatal("raw id stored")
		}
	}
}

func TestIdleTimeout(t *testing.T) {
	s, c := newTestStore()
	id := s.Create(7)
	c.add(29 * time.Minute)
	if _, err := s.Get(id); err != nil {
		t.Fatalf("active session rejected: %v", err)
	}
	c.add(31 * time.Minute) // 31 min since last activity
	if _, err := s.Get(id); !errors.Is(err, ErrNotFound) {
		t.Fatalf("idle session accepted: %v", err)
	}
}

func TestAbsoluteTimeout(t *testing.T) {
	s, c := newTestStore()
	id := s.Create(7)
	for range 25 { // active every 29 minutes for ~12 hours
		c.add(29 * time.Minute)
		if _, err := s.Get(id); err != nil {
			if c.t.Sub(time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)) <= 12*time.Hour {
				t.Fatalf("rejected before absolute timeout: %v", err)
			}
			return
		}
	}
	t.Fatal("session survived the absolute timeout")
}

func TestRotateInvalidatesOldID(t *testing.T) {
	s, _ := newTestStore()
	anon := s.Create(0)
	authed := s.Rotate(anon, 7)
	if anon == authed {
		t.Fatal("rotation kept the id")
	}
	if _, err := s.Get(anon); !errors.Is(err, ErrNotFound) {
		t.Fatal("pre-login id still valid: session fixation possible")
	}
	if sess, err := s.Get(authed); err != nil || sess.UserID != 7 {
		t.Fatalf("new id: %+v %v", sess, err)
	}
}

func TestDestroyUser(t *testing.T) {
	s, _ := newTestStore()
	a, b := s.Create(7), s.Create(7)
	other := s.Create(8)
	if n := s.DestroyUser(7); n != 2 {
		t.Fatalf("removed %d", n)
	}
	for _, id := range []string{a, b} {
		if _, err := s.Get(id); err == nil {
			t.Fatal("session survived DestroyUser")
		}
	}
	if _, err := s.Get(other); err != nil {
		t.Fatal("other user's session removed")
	}
}

func TestCookieFlags(t *testing.T) {
	rec := httptest.NewRecorder()
	http.SetCookie(rec, Cookie("abc"))
	got := rec.Header().Get("Set-Cookie")
	want := "__Host-sid=abc; Path=/; HttpOnly; Secure; SameSite=Lax"
	if got != want {
		t.Fatalf("Set-Cookie = %q\nwant         %q", got, want)
	}
	rec = httptest.NewRecorder()
	http.SetCookie(rec, ClearCookie())
	if got := rec.Header().Get("Set-Cookie"); !strings.Contains(got, "Max-Age=0") {
		t.Fatalf("clear cookie = %q", got)
	}
}

func TestLoadMiddleware(t *testing.T) {
	s, _ := newTestStore()
	id := s.Create(42)
	h := s.Load(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		sess, ok := From(r.Context())
		if !ok {
			http.Error(w, "anonymous", http.StatusUnauthorized)
			return
		}
		w.Write([]byte{byte(sess.UserID)})
	}))
	req := httptest.NewRequest("GET", "/", nil)
	req.AddCookie(&http.Cookie{Name: CookieName, Value: id})
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	if rec.Code != 200 || rec.Body.Bytes()[0] != 42 {
		t.Fatalf("code %d", rec.Code)
	}
	req = httptest.NewRequest("GET", "/", nil)
	req.AddCookie(&http.Cookie{Name: CookieName, Value: "forged"})
	rec = httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("forged id: code %d", rec.Code)
	}
}

alexedwards/scs and gorilla/sessions Important ​

In plain words: You rarely write the session store yourself. alexedwards/scs is a server-side session manager with pluggable stores; gorilla/sessions is mostly used for signed (and optionally encrypted) cookie sessions, where the data lives in the cookie itself.

Common misunderstanding: "A signed cookie session is the same as a server-side session." A signed cookie proves the data was not tampered with; it does not let you revoke it, because there is nothing on the server to delete. Until it expires, a copied cookie keeps working after logout. Another one: "scs defaults are production-ready." Cookie.Secure defaults to false and IdleTimeout to 0; set both.

Definition: scs v2: scs.New() returns a *SessionManager with Lifetime (24 h default), IdleTimeout, a Cookie struct (Name, Domain, HttpOnly, Path, Persist, SameSite, Secure, Partitioned), HashTokenInStore, and stores such as memstore (default), postgresstore, redisstore. The README: "Session data is stored on the server, and a randomly-generated unique session token (or session ID) is communicated to and from the client in a session cookie." LoadAndSave is the middleware; RenewToken(ctx) rotates ("To help prevent session fixation attacks you should renew the session token after any privilege level change"); Destroy(ctx) deletes the data. gorilla/sessions: "cookie and filesystem sessions and infrastructure for custom session backends", "signed (and optionally encrypted) cookies", key rotation through securecookie.CodecsFromPairs; v1.4.0 requires Go 1.23 "because of the new partitioned attribute".

scs request cycle (LoadAndSave)
1  read cookie "__Host-session" -> token
2  store.Find(sha256(token))    -> session data (or new empty session)
3  handler: sm.RenewToken(ctx); sm.Put(ctx, "userID", 7)
4  after handler: store.Commit(sha256(newToken), data, expiry); store.Delete(old)
5  Set-Cookie: __Host-session=<new token>; Path=/; HttpOnly; Secure; SameSite=Lax

Real scenario: a server-rendered Go app on PostgreSQL using postgresstore; a fleet behind a load balancer sharing redisstore; a small internal tool with a gorilla cookie store and no database; a "remember me" checkbox implemented with scs RememberMe.

PackageData livesRevocableRotationStore options
Hand-written (session here)ServerYesRotateWhatever you write
alexedwards/scs/v2 v2.9.0ServerYesRenewTokenmemstore, Redis, PostgreSQL, MySQL, SQLite, BoltDB, others
gorilla/sessions CookieStoreCookie (signed, optionally AES-encrypted)No (until expiry)Keys via CodecsFromPairsn/a
gorilla/sessions FilesystemStoreServer diskYesManualLocal files

Fix / how to use it:

go
// Package scsdemo shows the same session rules with github.com/alexedwards/scs/v2:
// server-side data, RenewToken on login and logout, idle and absolute timeouts.
package scsdemo

import (
	"net/http"
	"time"

	"github.com/alexedwards/scs/v2"
)

// NewManager configures scs v2.9.0. The in-memory store is the default;
// production uses postgresstore, redisstore, etc.
func NewManager() *scs.SessionManager {
	sm := scs.New()
	sm.Lifetime = 12 * time.Hour      // absolute timeout
	sm.IdleTimeout = 30 * time.Minute // idle timeout (0 = none by default)
	sm.Cookie.Name = "__Host-session"
	sm.Cookie.HttpOnly = true // default true
	sm.Cookie.Secure = true   // default false: always set it
	sm.Cookie.SameSite = http.SameSiteLaxMode
	sm.Cookie.Persist = false // browser-session cookie
	sm.HashTokenInStore = true
	return sm
}

// Routes wires login, logout and a page that needs the user id. Credential
// checking is out of scope here (see package after).
func Routes(sm *scs.SessionManager) http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /login", func(w http.ResponseWriter, r *http.Request) {
		// ... verify credentials first ...
		if err := sm.RenewToken(r.Context()); err != nil { // new token: no fixation
			http.Error(w, "internal error", http.StatusInternalServerError)
			return
		}
		sm.Put(r.Context(), "userID", int64(7))
		w.WriteHeader(http.StatusNoContent)
	})
	mux.HandleFunc("POST /logout", func(w http.ResponseWriter, r *http.Request) {
		if err := sm.Destroy(r.Context()); err != nil { // deletes server-side data
			http.Error(w, "internal error", http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusNoContent)
	})
	mux.HandleFunc("GET /me", func(w http.ResponseWriter, r *http.Request) {
		id := sm.GetInt64(r.Context(), "userID")
		if id == 0 {
			http.Error(w, "unauthenticated", http.StatusUnauthorized)
			return
		}
		w.Write([]byte("user 7"))
	})
	return sm.LoadAndSave(mux)
}
go
package scsdemo

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func cookieFrom(t *testing.T, rec *httptest.ResponseRecorder) *http.Cookie {
	t.Helper()
	for _, c := range rec.Result().Cookies() {
		if c.Name == "__Host-session" {
			return c
		}
	}
	return nil
}

func do(h http.Handler, method, path string, c *http.Cookie) *httptest.ResponseRecorder {
	req := httptest.NewRequest(method, path, nil)
	if c != nil {
		req.AddCookie(&http.Cookie{Name: c.Name, Value: c.Value})
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec
}

func TestLoginRenewsTokenAndLogoutDestroys(t *testing.T) {
	sm := NewManager()
	h := Routes(sm)

	pre := do(h, "GET", "/me", nil)
	if pre.Code != http.StatusUnauthorized {
		t.Fatalf("anonymous /me = %d", pre.Code)
	}

	login := do(h, "POST", "/login", nil)
	c := cookieFrom(t, login)
	if c == nil {
		t.Fatal("no session cookie after login")
	}
	raw := login.Header().Get("Set-Cookie")
	for _, flag := range []string{"HttpOnly", "Secure", "SameSite=Lax", "Path=/"} {
		if !strings.Contains(raw, flag) {
			t.Errorf("Set-Cookie %q lacks %s", raw, flag)
		}
	}
	if strings.Contains(raw, "Expires") {
		t.Errorf("Persist=false should give a browser-session cookie: %q", raw)
	}
	if got := do(h, "GET", "/me", c); got.Code != 200 {
		t.Fatalf("/me with session = %d", got.Code)
	}

	// A second login renews the token: the old one stops working.
	again := do(h, "POST", "/login", c)
	c2 := cookieFrom(t, again)
	if c2 == nil || c2.Value == c.Value {
		t.Fatal("RenewToken did not change the token")
	}
	if got := do(h, "GET", "/me", c); got.Code != http.StatusUnauthorized {
		t.Fatalf("old token still valid after renew: %d", got.Code)
	}

	if got := do(h, "POST", "/logout", c2); got.Code != http.StatusNoContent {
		t.Fatalf("logout = %d", got.Code)
	}
	if got := do(h, "GET", "/me", c2); got.Code != http.StatusUnauthorized {
		t.Fatalf("token valid after logout: %d", got.Code)
	}
}

JWT with golang-jwt/jwt v5: algorithms and claims validation Must-know ​

In plain words: A JWT is a small JSON document (claims) with a signature. Anyone with the right key can check that the issuer wrote it and that it has not expired, without asking the issuer. That is its strength (no lookup) and its weakness (no take-backs).

Common misunderstanding: "The payload is encrypted." A JWS is base64url, readable by anyone; never put secrets or personal data in it beyond what the API needs. Second: "If the signature is valid, the token is valid." RFC 8725 lists what else must hold: the issuer is the one you expect, the audience includes you, exp has not passed. golang-jwt v5 checks exp, nbf and (with WithIssuedAt) iat by default, but iss and aud only when you ask with WithIssuer and WithAudience.

Definition: RFC 7519 registered claims: iss (issuer), sub (subject), aud (audience), exp (expiration: "the current date/time MUST be before the expiration date/time"), nbf (not before), iat (issued at), jti (JWT ID). HS256 is HMAC-SHA-256 with one shared secret: whoever can verify can also mint ("A key of the same size as the hash output (for instance, 256 bits for 'HS256') or larger MUST be used"; RFC 8725: human-memorizable passwords "MUST NOT be directly used as the key"). RS256 is RSA PKCS#1 v1.5 with SHA-256 (keys of "2048 bits or larger"); ES256 is ECDSA P-256; EdDSA is Ed25519 (jwt.SigningMethodEdDSA, 64-byte signatures, deterministic). Asymmetric algorithms let many services verify with a public key while only the issuer holds the private key. golang-jwt v5: jwt.NewParser(opts...) with WithValidMethods, WithIssuer, WithAudience (any of), WithAllAudiences, WithSubject, WithExpirationRequired, WithNotBeforeRequired, WithIssuedAt, WithLeeway, WithTimeFunc; ParseWithClaims(raw, &claims, keyFunc).

real token from this module (header and payload decoded, 357 bytes total)
1  header  {"alg":"EdDSA","kid":"2026-11","typ":"at+jwt"}
2  payload {"roles":["admin"],"iss":"https://auth.example.test","sub":"user:7","aud":["orders-api"],
           "exp":1795869332,"nbf":1795868732,"iat":1795868732,"jti":"01JDQ7"}
3  verify  alg in allow-list {EdDSA}? kid in key ring? typ == at+jwt?
4          Ed25519 signature ok? exp > now-30s? nbf, iat <= now+30s? iss == ...? "orders-api" in aud?
5  any "no"  -> 401; errors.Is(err, jwt.ErrTokenExpired) etc. for logs

Real scenario: an orders API that accepts tokens from a central auth service; a mobile app's access token sent as Authorization: Bearer; a service-to-service call where billing must reject a token minted for orders (aud); a gateway that verifies once and forwards identity in a header to internal services (and must strip that header from outside traffic).

AlgorithmKeyWho can mintSignature sizeGo SigningMethodUse
HS256Shared secret ≥ 256 bitsEvery verifier32 BSigningMethodHS256One service signs and verifies its own tokens
RS256RSA ≥ 2048 bitsPrivate key holder256 B (2048-bit)SigningMethodRS256Widest interoperability (most IdPs)
PS256RSA-PSSPrivate key holder256 BSigningMethodPS256RSA where PSS is required
ES256ECDSA P-256Private key holder64 BSigningMethodES256Compact, FIPS-friendly
EdDSAEd25519Private key holder64 BSigningMethodEdDSACompact, fast, no nonce pitfalls
noneNoneAnyone0SigningMethodNoneNever; v5 requires UnsafeAllowNoneSignatureType
Claimgolang-jwt v5 defaultOption to enforceError
expChecked if presentWithExpirationRequired()token is expired (ErrTokenExpired)
nbfChecked if presentWithNotBeforeRequired()token is not valid yet
iatNot checkedWithIssuedAt()token used before issued
audNot checkedWithAudience(...), WithAllAudiences(...)token has invalid audience
issNot checkedWithIssuer(...)token has invalid issuer
subNot checkedWithSubject(...)token has invalid subject
Clock skew0WithLeeway(d)applies to exp, nbf, iat

Fix / how to use it: the jwtauth package issues EdDSA tokens with kid and typ: at+jwt, and verifies with a parser that pins the algorithm and requires exp, iss and aud.

go
// Package jwtauth issues and verifies short-lived access tokens with
// github.com/golang-jwt/jwt/v5: EdDSA (Ed25519) signatures, a kid header for
// key rotation, a fixed algorithm allow-list, and required exp/iss/aud.
package jwtauth

import (
	"crypto/ed25519"
	"errors"
	"fmt"
	"sync"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

// Claims are the registered claims plus what the API needs for authorization.
type Claims struct {
	Roles []string `json:"roles,omitempty"`
	jwt.RegisteredClaims
}

// KeyRing holds the current signing key and every public key still accepted.
// Rotation: add a new key, start signing with it, keep the old public key
// until the longest-lived token signed with it has expired, then remove it.
type KeyRing struct {
	mu      sync.RWMutex
	current string
	private map[string]ed25519.PrivateKey
	public  map[string]ed25519.PublicKey
}

func NewKeyRing() *KeyRing {
	return &KeyRing{private: map[string]ed25519.PrivateKey{}, public: map[string]ed25519.PublicKey{}}
}

// Add stores a key pair under kid and makes it the signing key.
func (k *KeyRing) Add(kid string, priv ed25519.PrivateKey) {
	k.mu.Lock()
	defer k.mu.Unlock()
	k.private[kid] = priv
	k.public[kid] = priv.Public().(ed25519.PublicKey)
	k.current = kid
}

// Retire stops accepting tokens signed with kid.
func (k *KeyRing) Retire(kid string) {
	k.mu.Lock()
	defer k.mu.Unlock()
	delete(k.private, kid)
	delete(k.public, kid)
}

// Public returns a copy of the accepted public keys (for a JWKS endpoint).
func (k *KeyRing) Public() map[string]ed25519.PublicKey {
	k.mu.RLock()
	defer k.mu.RUnlock()
	out := make(map[string]ed25519.PublicKey, len(k.public))
	for kid, pub := range k.public {
		out[kid] = pub
	}
	return out
}

// Issuer signs and verifies access tokens.
type Issuer struct {
	Keys     *KeyRing
	Issuer   string        // iss, e.g. "https://auth.example.test"
	Audience string        // aud, e.g. "orders-api"
	TTL      time.Duration // 5 to 15 minutes for access tokens
	Now      func() time.Time
}

// Issue returns a compact JWS: header.payload.signature.
func (is *Issuer) Issue(subject, jti string, roles []string) (string, error) {
	is.Keys.mu.RLock()
	kid, priv := is.Keys.current, is.Keys.private[is.Keys.current]
	is.Keys.mu.RUnlock()
	if priv == nil {
		return "", errors.New("jwtauth: no signing key")
	}
	now := is.Now()
	c := Claims{
		Roles: roles,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    is.Issuer,
			Subject:   subject,
			Audience:  jwt.ClaimStrings{is.Audience},
			ExpiresAt: jwt.NewNumericDate(now.Add(is.TTL)),
			NotBefore: jwt.NewNumericDate(now),
			IssuedAt:  jwt.NewNumericDate(now),
			ID:        jti, // lets a denylist revoke this one token
		},
	}
	t := jwt.NewWithClaims(jwt.SigningMethodEdDSA, c)
	t.Header["kid"] = kid
	t.Header["typ"] = "at+jwt" // explicit typing (RFC 8725 section 3.11, RFC 9068)
	return t.SignedString(priv)
}

// Verify parses and validates. The algorithm comes from our allow-list, the
// key from our ring by kid, never from anything else in the token.
func (is *Issuer) Verify(raw string) (*Claims, error) {
	p := jwt.NewParser(
		jwt.WithValidMethods([]string{jwt.SigningMethodEdDSA.Alg()}), // blocks alg confusion and "none"
		jwt.WithIssuer(is.Issuer),
		jwt.WithAudience(is.Audience),
		jwt.WithExpirationRequired(),
		jwt.WithIssuedAt(),
		jwt.WithLeeway(30*time.Second), // clock skew between hosts
		jwt.WithTimeFunc(is.Now),
	)
	var c Claims
	_, err := p.ParseWithClaims(raw, &c, func(t *jwt.Token) (any, error) {
		if typ, _ := t.Header["typ"].(string); typ != "at+jwt" {
			return nil, fmt.Errorf("unexpected typ %q", typ)
		}
		kid, _ := t.Header["kid"].(string)
		is.Keys.mu.RLock()
		pub, ok := is.Keys.public[kid] // map lookup: kid is never used in SQL or a path
		is.Keys.mu.RUnlock()
		if !ok {
			return nil, fmt.Errorf("unknown kid %q", kid)
		}
		return pub, nil
	})
	if err != nil {
		return nil, err
	}
	return &c, nil
}

Alg confusion and key rotation with kid Must-know ​

In plain words: The token tells you which algorithm it claims to use. If your code believes it, an attacker picks the algorithm. Decide the algorithm yourself, per key, and use kid only to pick which of your own keys to try.

Common misunderstanding: "golang-jwt checks the key type, so I am safe without WithValidMethods." The README: "This library attempts to make it easy to do the right thing by requiring key types to match the expected alg, but you should take the extra step to verify it in your usage." A keyfunc that returns []byte for some path (for an HS256 legacy client) reopens the hole for every token. And kid is attacker-controlled input: RFC 8725 warns it must not "create SQL or LDAP injection vulnerabilities", and following a jku or x5u URL from the header "could result in server-side request forgery (SSRF) attacks".

Definition: alg confusion (RFC 8725 section 2.1): "The algorithm can be changed to 'none' by an attacker", or "An 'RS256' ... parameter value can be changed into 'HS256' ... and some libraries would try to validate the signature using HMAC-SHA256 and using the RSA public key as the HMAC shared secret". Mitigation (section 3.1): "Libraries MUST enable the caller to specify a supported set of algorithms and MUST NOT use any other algorithms when performing cryptographic operations... each key MUST be used with exactly one algorithm". Key rotation with kid: the issuer signs with the newest key and puts its ID in the kid header; verifiers keep a set of accepted public keys; an old key is retired only after the longest-lived token signed with it has expired. Explicit typing (typ, section 3.11) keeps an ID token or a refresh token from being accepted as an access token; RFC 9068 defines at+jwt for OAuth access tokens.

attacker has: the public key (it is public) and one valid token
1  header {"alg":"HS256","kid":"2026-11","typ":"at+jwt"}  payload {"sub":"attacker","roles":["admin"],...}
2  sig = HMAC-SHA256(key = bytes of the Ed25519 public key, header.payload)
3  naive verifier: alg says HS256 -> HMAC with "the key" -> match -> admin
4  this module:  WithValidMethods(["EdDSA"]) -> "token signature is invalid: signing method HS256 is invalid"
5  "alg":"none" -> rejected the same way (and v5 refuses none without UnsafeAllowNoneSignatureType)
rotation:  ring {2026-11}  ->  Add 2026-12 (signs now)  ->  both verify  ->  Retire 2026-11 after max TTL

Real scenario: a library upgrade that changed a keyfunc default; a multi-tenant API that looks up the tenant's key by kid from a database (parameterise the query, or better, use a map); quarterly key rotation at an identity provider; an incident response that retires a leaked signing key immediately and accepts the forced logouts.

RiskHeader fieldMitigation
nonealgAllow-list; v5 needs UnsafeAllowNoneSignatureType
RS256/ES256/EdDSA → HS256algWithValidMethods with one family; keyfunc returns only asymmetric keys
Injection via key lookupkidMap lookup or parameterised query; length and charset check
SSRF via key URLjku, x5uIgnore them; JWKS URL comes from config
Token type substitutiontyp, audRequire typ and audience per token kind
Leaked signing keykidRetire the kid; tokens signed with it fail at once

Fix / how to use it: the tests forge an HS256 token with the public key bytes and a none token, check both fail, and walk a rotation from one key to the next.

go
package jwtauth

import (
	"crypto/ed25519"
	"crypto/rand"
	"errors"
	"strings"
	"testing"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

func newIssuer(t *testing.T, now *time.Time) *Issuer {
	t.Helper()
	_, priv, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	ring := NewKeyRing()
	ring.Add("2026-11", priv)
	return &Issuer{Keys: ring, Issuer: "https://auth.example.test", Audience: "orders-api",
		TTL: 10 * time.Minute, Now: func() time.Time { return *now }}
}

func TestIssueVerify(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	is := newIssuer(t, &now)
	tok, err := is.Issue("user:7", "jti-1", []string{"admin"})
	if err != nil {
		t.Fatal(err)
	}
	if strings.Count(tok, ".") != 2 {
		t.Fatalf("not a compact JWS: %s", tok)
	}
	c, err := is.Verify(tok)
	if err != nil {
		t.Fatal(err)
	}
	if c.Subject != "user:7" || c.Roles[0] != "admin" || c.ID != "jti-1" {
		t.Fatalf("claims %+v", c)
	}
}

func TestExpiredAndWrongAudience(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	is := newIssuer(t, &now)
	tok, _ := is.Issue("user:7", "jti-2", nil)

	now = now.Add(10*time.Minute + 29*time.Second) // inside the 30 s leeway
	if _, err := is.Verify(tok); err != nil {
		t.Fatalf("leeway: %v", err)
	}
	now = now.Add(2 * time.Second)
	if _, err := is.Verify(tok); !errors.Is(err, jwt.ErrTokenExpired) {
		t.Fatalf("err = %v, want ErrTokenExpired", err)
	}

	now = time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	other := *is
	other.Audience = "billing-api"
	if _, err := other.Verify(tok); !errors.Is(err, jwt.ErrTokenInvalidAudience) {
		t.Fatalf("err = %v, want ErrTokenInvalidAudience", err)
	}
}

// The classic alg confusion: re-sign the token with HS256 using the public
// key bytes as the HMAC secret. A parser that trusted "alg" would accept it.
func TestAlgConfusionRejected(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	is := newIssuer(t, &now)
	pub := is.Keys.Public()["2026-11"]

	forged := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{
		Roles: []string{"admin"},
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer: is.Issuer, Subject: "attacker", Audience: jwt.ClaimStrings{is.Audience},
			ExpiresAt: jwt.NewNumericDate(now.Add(time.Hour)), IssuedAt: jwt.NewNumericDate(now),
		},
	})
	forged.Header["kid"] = "2026-11"
	forged.Header["typ"] = "at+jwt"
	raw, err := forged.SignedString([]byte(pub))
	if err != nil {
		t.Fatal(err)
	}
	if _, err := is.Verify(raw); !errors.Is(err, jwt.ErrTokenSignatureInvalid) {
		t.Fatalf("HS256 forgery: err = %v, want ErrTokenSignatureInvalid", err)
	}

	none := jwt.NewWithClaims(jwt.SigningMethodNone, forged.Claims)
	none.Header["kid"] = "2026-11"
	none.Header["typ"] = "at+jwt"
	rawNone, _ := none.SignedString(jwt.UnsafeAllowNoneSignatureType)
	if _, err := is.Verify(rawNone); err == nil {
		t.Fatal(`"alg":"none" accepted`)
	}
}

func TestKeyRotation(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	is := newIssuer(t, &now)
	old, _ := is.Issue("user:7", "a", nil)

	_, next, _ := ed25519.GenerateKey(rand.Reader)
	is.Keys.Add("2026-12", next)
	fresh, _ := is.Issue("user:7", "b", nil)

	for _, tok := range []string{old, fresh} {
		if _, err := is.Verify(tok); err != nil {
			t.Fatalf("during overlap: %v", err)
		}
	}
	is.Keys.Retire("2026-11")
	if _, err := is.Verify(old); err == nil {
		t.Fatal("token signed with a retired key accepted")
	}
	if _, err := is.Verify(fresh); err != nil {
		t.Fatal(err)
	}
}

func TestTamperedPayload(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	is := newIssuer(t, &now)
	tok, _ := is.Issue("user:7", "c", nil)
	parts := strings.Split(tok, ".")
	parts[1] = parts[1][:len(parts[1])-2] + "xx"
	if _, err := is.Verify(strings.Join(parts, ".")); err == nil {
		t.Fatal("tampered payload accepted")
	}
}

Short-lived access + refresh tokens and revocation Must-know ​

In plain words: Because a JWT cannot be cancelled, make it expire soon (minutes), and give the client a second, long-lived, opaque token that it can trade for a new access token. The second token is checked against a database on every use, so that is where logout, password reset and theft detection happen.

Common misunderstanding: "Refresh tokens are just longer JWTs." Make them opaque random strings stored (hashed) on the server: they are used rarely, so a lookup costs nothing, and a lookup is exactly what makes them revocable. Second: "rotation is enough." Rotation without reuse detection only shortens the window; RFC 9700 couples them: "If a refresh token is compromised and subsequently used by both the attacker and the legitimate client, one of them will present an invalidated refresh token, which will inform the authorization server of the breach."

Definition: short-lived access + refresh tokens: access token TTL 5-15 minutes, refresh token TTL days to weeks, both bound to a client and audience. Refresh token rotation (RFC 9700 section 4.14.2): "the authorization server issues a new refresh token with every access token refresh response. The previous refresh token is invalidated, but information about the relationship is retained", and on reuse "it will revoke the active refresh token". For public clients (SPAs, mobile), refresh tokens "MUST be sender-constrained or use refresh token rotation". Revocation of an access token before exp needs state: a jti denylist whose entries live until the token's own exp (a Redis key with TTL), a per-user "tokens issued before T are invalid" timestamp, or the token status lists described in the OWASP JWT cheat sheet.

t=0      login                      -> A1 (10 min), R1 (30 days, family F)        store sha256(R1)
t=10m    POST /token R1             -> A2, R2; R1 marked used
t=12m    attacker POST /token R1    -> R1 used: reuse! revoke family F            ErrReused
t=13m    client POST /token R2      -> family revoked: 401, log in again           ErrInvalid
t=14m    A2 still verifies at the API until t=20m unless its jti is on the denylist
Refresh token rotation: a used token presented twice kills the familyClientAuth server (family F)Attackert=0 login (password + MFA)A1 (JWT, 10 min) + R1 (opaque, 30 days)store sha256(R1): family F, unusedR1 leaks (XSS, log, backup)t=10 min: A1 expired, POST /token R1A2 + R2R1 marked used, R2 stored in Freplays R1R1 already used: reuse detected, revoke family Fserver cannot tell thief from owner, so both loselater: POST /token R2401 invalid_grant: log in againIf the thief had rotated first, the owner's replayof R1 triggers the same revocation.

Real scenario: a mobile app that stays logged in for a month but whose access token expires every 10 minutes; a stolen refresh token from an XSS'd SPA, detected on the next legitimate refresh; "log out of all devices" after a password change; an admin disabling an account while the user's access token still has 8 minutes left (denylist the jti, or accept the window).

MechanismRevokesState neededDelay until effective
Short access TTLEverything, eventuallyNoneUp to the TTL (10 min here)
Refresh token deletionFuture access tokensRefresh token tableUp to one access TTL
Rotation + reuse detectionA stolen refresh token familyUsed flag + family idNext refresh by either party
jti denylistOne access tokenKey per revoked token until expImmediate (checked per request)
"Not before" per userAll tokens issued before TOne timestamp per userImmediate (one lookup per request)
Key retirement (kid)Every token signed with that keyKey ringImmediate, for everyone on that key

Fix / how to use it: the refresh package stores only hashes, rotates under a lock (in SQL: one transaction with SELECT ... FOR UPDATE), revokes the family on reuse, and has a jti denylist that prunes itself at exp. The concurrency test proves that 20 simultaneous refreshes with one token produce exactly one winner.

go
// Package refresh implements opaque refresh tokens with rotation and reuse
// detection (RFC 9700 section 4.14.2), plus a jti denylist for revoking an
// access token before it expires.
package refresh

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"sync"
	"time"
)

var (
	ErrInvalid = errors.New("refresh: invalid or expired token")
	ErrReused  = errors.New("refresh: token reuse detected, family revoked")
)

type record struct {
	userID  int64
	family  string // one login = one family
	expires time.Time
	used    bool // rotated away; presenting it again means theft
}

// Store keeps only SHA-256(token): a stolen table is not a list of tokens.
// In SQL the Rotate critical section is one transaction with SELECT ... FOR
// UPDATE on the row (see the page's schema).
type Store struct {
	mu      sync.Mutex
	byHash  map[string]*record
	revoked map[string]bool // revoked families
	TTL     time.Duration   // e.g. 30 days, sliding with each rotation
	Now     func() time.Time
}

func NewStore(ttl time.Duration) *Store {
	return &Store{byHash: map[string]*record{}, revoked: map[string]bool{}, TTL: ttl, Now: time.Now}
}

func newToken() string {
	b := make([]byte, 32)
	rand.Read(b)
	return hex.EncodeToString(b)
}

func digest(tok string) string {
	sum := sha256.Sum256([]byte(tok))
	return hex.EncodeToString(sum[:])
}

// Issue starts a new family at login.
func (s *Store) Issue(userID int64) string {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.issueLocked(userID, newToken())
}

func (s *Store) issueLocked(userID int64, family string) string {
	tok := newToken()
	s.byHash[digest(tok)] = &record{userID: userID, family: family, expires: s.Now().Add(s.TTL)}
	return tok
}

// Rotate consumes tok and returns its successor. Exactly one concurrent
// caller can win; a second presentation of a used token revokes the family.
func (s *Store) Rotate(tok string) (userID int64, next string, err error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	rec, ok := s.byHash[digest(tok)]
	if !ok || s.revoked[rec.family] || s.Now().After(rec.expires) {
		return 0, "", ErrInvalid
	}
	if rec.used {
		s.revoked[rec.family] = true // attacker and victim both lose; victim logs in again
		return 0, "", ErrReused
	}
	rec.used = true
	return rec.userID, s.issueLocked(rec.userID, rec.family), nil
}

// RevokeUser ends every family of a user (logout everywhere, password reset).
func (s *Store) RevokeUser(userID int64) {
	s.mu.Lock()
	defer s.mu.Unlock()
	for _, r := range s.byHash {
		if r.userID == userID {
			s.revoked[r.family] = true
		}
	}
}

// Denylist revokes individual access tokens by jti until their exp. Entries
// expire with the token, so the list stays as small as the access TTL allows.
type Denylist struct {
	mu  sync.Mutex
	ids map[string]time.Time // jti -> token exp
	Now func() time.Time
}

func NewDenylist() *Denylist { return &Denylist{ids: map[string]time.Time{}, Now: time.Now} }

func (d *Denylist) Revoke(jti string, exp time.Time) {
	d.mu.Lock()
	d.ids[jti] = exp
	d.mu.Unlock()
}

// Revoked is checked by the API after signature and claims validation.
func (d *Denylist) Revoked(jti string) bool {
	d.mu.Lock()
	defer d.mu.Unlock()
	now := d.Now()
	for id, exp := range d.ids { // a Redis key with TTL does this for free
		if now.After(exp) {
			delete(d.ids, id)
		}
	}
	_, ok := d.ids[jti]
	return ok
}
go
package refresh

import (
	"errors"
	"sync"
	"testing"
	"time"
)

func TestRotateChain(t *testing.T) {
	s := NewStore(30 * 24 * time.Hour)
	t1 := s.Issue(7)
	uid, t2, err := s.Rotate(t1)
	if err != nil || uid != 7 || t2 == t1 {
		t.Fatalf("uid=%d err=%v", uid, err)
	}
	if _, _, err := s.Rotate(t2); err != nil {
		t.Fatal(err)
	}
}

func TestReuseRevokesFamily(t *testing.T) {
	s := NewStore(time.Hour)
	stolen := s.Issue(7)
	_, legit, _ := s.Rotate(stolen) // the real client rotates first
	if _, _, err := s.Rotate(stolen); !errors.Is(err, ErrReused) {
		t.Fatalf("replay: err = %v, want ErrReused", err)
	}
	if _, _, err := s.Rotate(legit); !errors.Is(err, ErrInvalid) {
		t.Fatalf("family should be revoked: err = %v", err)
	}
	other := s.Issue(7) // a new login is a new family
	if _, _, err := s.Rotate(other); err != nil {
		t.Fatal(err)
	}
}

func TestConcurrentRotateHasOneWinner(t *testing.T) {
	s := NewStore(time.Hour)
	tok := s.Issue(7)
	var wg sync.WaitGroup
	var mu sync.Mutex
	wins := 0
	for range 20 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if _, _, err := s.Rotate(tok); err == nil {
				mu.Lock()
				wins++
				mu.Unlock()
			}
		}()
	}
	wg.Wait()
	if wins != 1 {
		t.Fatalf("%d winners, want 1", wins)
	}
}

func TestExpiryAndRevokeUser(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	s := NewStore(time.Hour)
	s.Now = func() time.Time { return now }
	tok := s.Issue(7)
	now = now.Add(61 * time.Minute)
	if _, _, err := s.Rotate(tok); !errors.Is(err, ErrInvalid) {
		t.Fatalf("expired: %v", err)
	}
	now = now.Add(time.Minute)
	tok = s.Issue(7)
	s.RevokeUser(7)
	if _, _, err := s.Rotate(tok); !errors.Is(err, ErrInvalid) {
		t.Fatalf("after RevokeUser: %v", err)
	}
}

func TestDenylist(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	d := NewDenylist()
	d.Now = func() time.Time { return now }
	d.Revoke("jti-1", now.Add(10*time.Minute))
	if !d.Revoked("jti-1") || d.Revoked("jti-2") {
		t.Fatal("denylist lookup wrong")
	}
	now = now.Add(11 * time.Minute) // the token itself has expired by now
	if d.Revoked("jti-1") || len(d.ids) != 0 {
		t.Fatal("entry not pruned after exp")
	}
}

JWKS fetching Important ​

In plain words: A JWK Set is a JSON list of public keys at a well-known URL. Verifiers download it, cache it, and look up the key named by the token's kid. When the issuer rotates, verifiers see an unknown kid and fetch the list again.

Common misunderstanding: "Fetch the JWKS on every request" (slow, and the issuer becomes a single point of failure) or "fetch it once at startup" (the first rotation breaks every verifier). Cache it, refresh on unknown kid, but rate-limit that refresh: otherwise a stream of tokens with random kid values turns your API into a denial-of-service tool against the issuer.

Definition: RFC 7517: a JWK Set has "a 'keys' member, which is an array of JWKs"; "The 'kid' (key ID) parameter is used to match a specific key." An Ed25519 key is {"kty":"OKP","crv":"Ed25519","x":"<base64url>","kid":"...","alg":"EdDSA","use":"sig"} (RFC 8037). OpenID providers publish the URL as jwks_uri in their discovery document. MicahParks/keyfunc provides "An automatic refresh of remote HTTP resources when an unknown key ID (kid) is encountered" and returns a jwt.Keyfunc; the golang-jwt README lists it as the JWKS extension.

1  verify(token kid=k2)   cache {k1}            -> unknown kid
2  last attempt 2 min ago < MinRefresh 5 min    -> reject (no fetch: kid spraying is cheap for attackers)
3  6 min later            >= MinRefresh          -> GET https://auth.example.test/.well-known/jwks.json
4                         cache {k1, k2}         -> verify with k2
5  token kid=nope         just attempted         -> reject without another fetch
6  issuer removes k1; 6 min later, token kid=k1 -> attempt is due: refetch -> {k2} -> k1 rejected
7  issuer returns 500     attempt recorded       -> next attempt only after MinRefresh; last good set kept

Real scenario: every service in a fleet verifying tokens from Auth0, Keycloak, Cognito or an in-house issuer; an issuer outage during which cached keys keep APIs working; a key rotation at the IdP on a Tuesday afternoon that nobody notices, because verifiers refresh on unknown kid.

ConcernHandling herekeyfunc
URL sourceConfig only; jku ignoredConfig
Unknown kidRefresh at most every MinRefreshRate-limited refresh on unknown kid
Removed kidEvery lookup re-validates the set once MinRefresh has passed; kids no longer published are droppedBackground refresh replaces the set
Issuer downFailed attempts also start the MinRefresh wait; the last good set stays in useRefresh errors handled by the library
Algorithm per keyOnly OKP/Ed25519/EdDSA keptPer-JWK alg
Response sizeMaxBytesReader 1 MiBLibrary limits
HTTPCache-Control: public, max-age=300 on the serverBackground refresh interval

Fix / how to use it:

go
// Package jwks publishes Ed25519 public keys as a JWK Set (RFC 7517, OKP
// keys per RFC 8037) and fetches them on the verifying side with a cache
// that refreshes on an unknown kid, at most once per MinRefresh.
// In production, github.com/MicahParks/keyfunc does the client half.
package jwks

import (
	"context"
	"crypto/ed25519"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"sync"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

type jwk struct {
	Kty string `json:"kty"` // "OKP"
	Crv string `json:"crv"` // "Ed25519"
	X   string `json:"x"`   // base64url public key
	Kid string `json:"kid"`
	Use string `json:"use"` // "sig"
	Alg string `json:"alg"` // "EdDSA"
}

type set struct {
	Keys []jwk `json:"keys"`
}

// Handler serves GET /.well-known/jwks.json from a key source.
func Handler(keys func() map[string]ed25519.PublicKey) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var s set
		for kid, pub := range keys() {
			s.Keys = append(s.Keys, jwk{Kty: "OKP", Crv: "Ed25519", Kid: kid, Use: "sig", Alg: "EdDSA",
				X: base64.RawURLEncoding.EncodeToString(pub)})
		}
		w.Header().Set("Content-Type", "application/jwk-set+json")
		w.Header().Set("Cache-Control", "public, max-age=300")
		json.NewEncoder(w).Encode(s)
	})
}

// Cache is the verifier side.
type Cache struct {
	URL        string // fixed in config: never taken from a jku header
	Client     *http.Client
	MinRefresh time.Duration // e.g. 5 * time.Minute; stops kid-spraying from DoS-ing the issuer
	Now        func() time.Time

	mu        sync.Mutex
	keys      map[string]ed25519.PublicKey
	attempted time.Time // last fetch attempt, successful or not
	Fetches   int       // successful fetches, for the test
}

func (c *Cache) refresh(ctx context.Context) error {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.URL, nil)
	if err != nil {
		return err
	}
	resp, err := c.Client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("jwks: status %d", resp.StatusCode)
	}
	var s set
	if err := json.NewDecoder(http.MaxBytesReader(nil, resp.Body, 1<<20)).Decode(&s); err != nil {
		return err
	}
	keys := map[string]ed25519.PublicKey{}
	for _, k := range s.Keys {
		if k.Kty != "OKP" || k.Crv != "Ed25519" || k.Alg != "EdDSA" {
			continue // only the one algorithm we accept
		}
		raw, err := base64.RawURLEncoding.DecodeString(k.X)
		if err != nil || len(raw) != ed25519.PublicKeySize {
			continue
		}
		keys[k.Kid] = ed25519.PublicKey(raw)
	}
	c.keys, c.Fetches = keys, c.Fetches+1
	return nil
}

// Key returns the key for kid. At most once per MinRefresh (counting failed
// attempts too) it re-fetches the set: that picks up new kids and drops kids
// the issuer no longer publishes, so a retired or compromised key stops
// verifying within MinRefresh. If the issuer is down, the last good set is
// kept, and the next attempt waits for MinRefresh again.
func (c *Cache) Key(ctx context.Context, kid string) (ed25519.PublicKey, error) {
	c.mu.Lock()
	defer c.mu.Unlock()
	now := c.Now()
	if c.attempted.IsZero() || now.Sub(c.attempted) >= c.MinRefresh {
		c.attempted = now
		if err := c.refresh(ctx); err != nil && c.keys == nil {
			return nil, err
		}
	}
	if k, ok := c.keys[kid]; ok {
		return k, nil
	}
	return nil, fmt.Errorf("jwks: unknown kid %q", kid)
}

// Keyfunc adapts the cache to golang-jwt. Pair it with
// jwt.WithValidMethods([]string{"EdDSA"}).
func (c *Cache) Keyfunc(ctx context.Context) jwt.Keyfunc {
	return func(t *jwt.Token) (any, error) {
		kid, ok := t.Header["kid"].(string)
		if !ok {
			return nil, errors.New("jwks: token has no kid")
		}
		return c.Key(ctx, kid)
	}
}
go
package jwks

import (
	"crypto/ed25519"
	"crypto/rand"
	"net/http/httptest"
	"sync"
	"testing"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

func TestFetchVerifyAndRotate(t *testing.T) {
	var mu sync.Mutex
	pubs := map[string]ed25519.PublicKey{}
	privs := map[string]ed25519.PrivateKey{}
	add := func(kid string) {
		pub, priv, _ := ed25519.GenerateKey(rand.Reader)
		mu.Lock()
		pubs[kid], privs[kid] = pub, priv
		mu.Unlock()
	}
	add("k1")
	srv := httptest.NewTLSServer(Handler(func() map[string]ed25519.PublicKey {
		mu.Lock()
		defer mu.Unlock()
		out := map[string]ed25519.PublicKey{}
		for k, v := range pubs {
			out[k] = v
		}
		return out
	}))
	defer srv.Close()

	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	c := &Cache{URL: srv.URL, Client: srv.Client(), MinRefresh: 5 * time.Minute,
		Now: func() time.Time { return now }}

	sign := func(kid string) string {
		tok := jwt.NewWithClaims(jwt.SigningMethodEdDSA, jwt.MapClaims{"sub": "user:7"})
		tok.Header["kid"] = kid
		mu.Lock()
		priv, ok := privs[kid]
		mu.Unlock()
		if !ok {
			priv = privs["k1"] // a token claiming a kid the issuer never published
		}
		s, err := tok.SignedString(priv)
		if err != nil {
			t.Fatal(err)
		}
		return s
	}
	parse := func(raw string) error {
		_, err := jwt.Parse(raw, c.Keyfunc(t.Context()), jwt.WithValidMethods([]string{"EdDSA"}))
		return err
	}

	if err := parse(sign("k1")); err != nil {
		t.Fatal(err)
	}
	if err := parse(sign("k1")); err != nil || c.Fetches != 1 {
		t.Fatalf("cached key: err=%v fetches=%d", err, c.Fetches)
	}

	add("k2") // issuer rotates
	if err := parse(sign("k2")); err == nil {
		t.Fatal("unknown kid accepted before MinRefresh elapsed")
	}
	now = now.Add(6 * time.Minute)
	if err := parse(sign("k2")); err != nil || c.Fetches != 2 {
		t.Fatalf("after refresh: err=%v fetches=%d", err, c.Fetches)
	}
	if err := parse(sign("nope")); err == nil || c.Fetches != 2 {
		t.Fatalf("kid spraying triggered a fetch: fetches=%d", c.Fetches)
	}
}

Two more tests pin the revocation and outage behaviour: a key removed from the published set stops verifying after MinRefresh, and five unknown kids during a 500 outage cause one fetch, not five.

go
package jwks

import (
	"crypto/ed25519"
	"crypto/rand"
	"net/http"
	"net/http/httptest"
	"sync"
	"sync/atomic"
	"testing"
	"time"
)

// A key removed from the issuer's set must stop verifying once MinRefresh
// has passed: the cache re-validates known kids against the published set.
func TestRemovedKeyStopsVerifying(t *testing.T) {
	var mu sync.Mutex
	pub, _, _ := ed25519.GenerateKey(rand.Reader)
	keys := map[string]ed25519.PublicKey{"k1": pub}
	srv := httptest.NewTLSServer(Handler(func() map[string]ed25519.PublicKey {
		mu.Lock()
		defer mu.Unlock()
		out := map[string]ed25519.PublicKey{}
		for k, v := range keys {
			out[k] = v
		}
		return out
	}))
	defer srv.Close()
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	c := &Cache{URL: srv.URL, Client: srv.Client(), MinRefresh: 5 * time.Minute, Now: func() time.Time { return now }}
	if _, err := c.Key(t.Context(), "k1"); err != nil {
		t.Fatal(err)
	}
	mu.Lock()
	delete(keys, "k1") // issuer retires a compromised key
	mu.Unlock()
	now = now.Add(6 * time.Minute)
	if _, err := c.Key(t.Context(), "k1"); err == nil {
		t.Fatal("key removed from the published set still verifies after MinRefresh")
	}
}

// During an issuer outage, unknown kids must not trigger one fetch each.
func TestFailedRefreshIsRateLimited(t *testing.T) {
	var hits atomic.Int64
	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		hits.Add(1)
		http.Error(w, "down", http.StatusInternalServerError)
	}))
	defer srv.Close()
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	c := &Cache{URL: srv.URL, Client: srv.Client(), MinRefresh: 5 * time.Minute, Now: func() time.Time { return now }}
	for _, kid := range []string{"a", "b", "c", "d", "e"} {
		if _, err := c.Key(t.Context(), kid); err == nil {
			t.Fatal("unknown kid accepted")
		}
	}
	if n := hits.Load(); n != 1 {
		t.Fatalf("%d fetches during the outage, want 1", n)
	}
	now = now.Add(6 * time.Minute)
	c.Key(t.Context(), "f")
	if n := hits.Load(); n != 2 {
		t.Fatalf("after MinRefresh: %d fetches, want 2", n)
	}
}

OAuth2 and OIDC clients: x/oauth2 and coreos/go-oidc (pointer) Good to know ​

In plain words: "Log in with Google/Microsoft/Okta" is OpenID Connect on top of OAuth 2.0. Your Go app redirects the user to the provider, gets a one-time code back, exchanges it for tokens, and verifies the ID token. Two packages do almost all of it.

Common misunderstanding: "The access token from the provider proves who the user is." The access token is for calling the provider's APIs; identity comes from the verified ID token (iss, aud = your client ID, exp, nonce). Another one: "OAuth is my login system." After the callback you still create your own session (this page) for your own app.

Definition: golang.org/x/oauth2: oauth2.Config{ClientID, ClientSecret, Endpoint, RedirectURL, Scopes}, AuthCodeURL(state, opts...), Exchange(ctx, code, opts...), and PKCE helpers GenerateVerifier(), S256ChallengeOption(verifier), VerifierOption(verifier). github.com/coreos/go-oidc/v3/oidc: oidc.NewProvider(ctx, issuerURL) reads the discovery document, provider.Verifier(&oidc.Config{ClientID: clientID}) returns an ID token verifier, and verifier.Verify(ctx, rawIDToken) checks signature (via the provider's JWKS), issuer, audience and expiry. The source is explicit about one gap: "Verify does NOT do nonce validation, which is the caller's responsibility"; send the nonce with oidc.Nonce(n) in AuthCodeURL and compare idToken.Nonce with the value kept in the pre-login session. The full protocol, flows and SSO design are in OAuth2, OIDC & SSO.

1  GET /login/google   -> state, PKCE verifier into the (pre-login) session
2  302 to provider     AuthCodeURL(state, S256ChallengeOption(verifier)) + scope openid email
3  GET /callback?code&state   -> state matches session? (CSRF on the login itself)
4  Exchange(ctx, code, VerifierOption(verifier)) -> oauth2.Token with "id_token" extra
5  verifier.Verify(ctx, rawIDToken) -> signature, iss, aud, exp; then YOU check idToken.Nonce == session nonce
6  find or create local user by (issuer, sub); Rotate session; Set-Cookie

Real scenario: a B2B SaaS that offers "Sign in with Microsoft" for enterprise tenants; an internal tool behind the company's Okta; a mobile app using the system browser with PKCE; a Go API that only verifies access tokens from Keycloak (then it is a resource server and needs JWKS, not go-oidc's login flow).

NeedPackageKey calls
Authorization code flow + PKCEgolang.org/x/oauth2AuthCodeURL, Exchange, GenerateVerifier, S256ChallengeOption
Provider discovery + ID token verificationgithub.com/coreos/go-oidc/v3/oidcNewProvider, Verifier, Verify, IDToken.Claims
Access token verification at an APIgolang-jwt/jwt/v5 + JWKS (keyfunc)WithValidMethods, WithIssuer, WithAudience
Client credentials (service to service)golang.org/x/oauth2/clientcredentialsConfig.Token, Config.Client

Fix / how to use it: keep state, the PKCE verifier and the nonce in the pre-login session; on the callback check state, Exchange with VerifierOption, Verify the ID token, compare the nonce yourself, map (iss, sub) to a local user (never the email alone), then Rotate the session exactly as after a password login. For an API that only receives access tokens, skip go-oidc and verify JWTs with JWKS.

Auth middleware, context identity and the authorization check per handler Must-know ​

In plain words: One middleware answers "who is this?" once per request and stores the answer in the request context under a key no other package can forge. Every handler then answers "may this caller do this to this object?" itself, after it has loaded the object.

Common misunderstanding: "RequireRole("user") on the route group is my authorization." It says the caller is a user; it says nothing about whether invoice 1001 belongs to them. OWASP API1:2023 (Broken Object Level Authorization) is exactly that gap. Second: "if the token is invalid, try the next scheme." If a request presents a credential that fails, reject it; falling through to an anonymous or weaker scheme turns a forged token into a downgrade.

Definition: authentication middleware wraps a handler (func(http.Handler) http.Handler, see Middlewares), extracts a credential (cookie via session.Load, or Authorization: Bearer via jwtauth.Verify), and on success calls next.ServeHTTP(w, r.WithContext(WithIdentity(ctx, id))); on failure it answers 401 with WWW-Authenticate. The context key is an unexported struct type (type ctxKey struct{}), so context.WithValue(ctx, "identity", ...) from any other package cannot impersonate it (the context rules are in context). Authorization per handler is the check after loading the object: ownership, tenant, state. 403 Forbidden means "known caller, not allowed"; for objects the caller may not even know exist, answer 404 so ids cannot be probed.

     request                          RequireUser(Bearer(verify))         InvoiceHandler
1    GET /invoices/1001, no token  -> 401 + WWW-Authenticate: Bearer realm="api"
2    Bearer forged                 -> verify fails -> 401 (no fallback to another scheme)
3    Bearer alice (user 1)         -> ctx{Identity{1}}  ───────────────▶ load 1001: owner 1 == 1 -> 200
4    Bearer bob (user 2)           -> ctx{Identity{2}}  ───────────────▶ load 1001: owner 1 != 2 -> 404
5    Bearer root (admin)           -> ctx{Identity{9, admin}} ──────────▶ admin -> 200
6    GET /admin/stats as alice     -> RequireRole("admin") -> 403

Real scenario: GET /api/orders/{id} in a marketplace where buyers could read other buyers' addresses by incrementing the id; a multi-tenant SaaS whose repository must filter by tenant_id from the identity, never from the request body; a support role that may read but not refund; a mobile endpoint that accepts both cookies (web view) and bearer tokens.

LayerAnswersStatus on failureWhere in Go
Authentication middlewareWho is calling?401 + WWW-AuthenticateRequireUser
Coarse authorization (route group)Is this caller's role allowed here at all?403RequireRole
Object authorization (handler)May this caller touch this object?404 (hide) or 403After Load, compare owner/tenant
Data layer guardDefence in depthEmpty resultWHERE id = $1 AND owner_id = $2
Field-levelMay this caller see this field?Omitted fieldResponse DTO per role

Fix / how to use it:

go
// Package authmw turns "who is calling" into a typed value in the request
// context (authentication), and leaves "may they do this" to each handler
// (authorization), with a small helper for role checks.
package authmw

import (
	"context"
	"errors"
	"net/http"
	"slices"
	"strings"
)

// Identity is what every handler may rely on after RequireUser.
type Identity struct {
	UserID int64
	Roles  []string
	Method string // "session" or "bearer": some actions demand a session
}

func (id *Identity) Has(role string) bool { return slices.Contains(id.Roles, role) }

type ctxKey struct{} // unexported: no other package can read or forge it

func WithIdentity(ctx context.Context, id *Identity) context.Context {
	return context.WithValue(ctx, ctxKey{}, id)
}

// From returns the caller, or nil for anonymous requests.
func From(ctx context.Context) *Identity {
	id, _ := ctx.Value(ctxKey{}).(*Identity)
	return id
}

// ErrNoCredentials means "nothing presented"; any other error means
// "something presented and it was wrong". Both answer 401.
var ErrNoCredentials = errors.New("authmw: no credentials")

// Authenticator checks one kind of credential (session cookie, bearer JWT).
type Authenticator func(r *http.Request) (*Identity, error)

// Bearer extracts "Authorization: Bearer <token>" and hands it to verify.
func Bearer(verify func(token string) (*Identity, error)) Authenticator {
	return func(r *http.Request) (*Identity, error) {
		h := r.Header.Get("Authorization")
		scheme, tok, ok := strings.Cut(h, " ")
		if !ok || !strings.EqualFold(scheme, "Bearer") || tok == "" {
			return nil, ErrNoCredentials
		}
		id, err := verify(tok)
		if err != nil {
			return nil, err
		}
		id.Method = "bearer"
		return id, nil
	}
}

// RequireUser tries each authenticator in order and rejects with 401 when
// none succeeds. The error detail goes to logs, never to the client.
func RequireUser(auths ...Authenticator) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			for _, a := range auths {
				id, err := a(r)
				if errors.Is(err, ErrNoCredentials) {
					continue
				}
				if err != nil {
					break // a wrong credential: do not fall through to the next scheme
				}
				next.ServeHTTP(w, r.WithContext(WithIdentity(r.Context(), id)))
				return
			}
			w.Header().Set("WWW-Authenticate", `Bearer realm="api"`)
			http.Error(w, "authentication required", http.StatusUnauthorized)
		})
	}
}

// RequireRole is coarse-grained authorization for a whole route group.
func RequireRole(role string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			id := From(r.Context())
			if id == nil {
				http.Error(w, "authentication required", http.StatusUnauthorized)
				return
			}
			if !id.Has(role) {
				http.Error(w, "forbidden", http.StatusForbidden)
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}
go
package authmw

import (
	"encoding/json"
	"net/http"
	"strconv"
)

type Invoice struct {
	ID      int64 `json:"id"`
	OwnerID int64 `json:"owner_id"`
	Total   int64 `json:"total_cents"`
}

// InvoiceHandler shows the check no middleware can do for you: the object's
// owner is only known after loading it. Skipping it is IDOR / BOLA, the
// first item (API1:2023) of the OWASP API Security Top 10.
type InvoiceHandler struct {
	Load func(id int64) (Invoice, bool)
}

func (h InvoiceHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	me := From(r.Context()) // set by RequireUser
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	inv, ok := h.Load(id)
	// Same 404 for "does not exist" and "not yours": do not confirm that
	// invoice 1002 exists to someone who may not see it. Admins see all.
	if !ok || (inv.OwnerID != me.UserID && !me.Has("admin")) {
		http.NotFound(w, r)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(inv)
}
go
package authmw

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
)

func routes() http.Handler {
	verify := func(tok string) (*Identity, error) {
		switch tok {
		case "alice":
			return &Identity{UserID: 1}, nil
		case "bob":
			return &Identity{UserID: 2}, nil
		case "root":
			return &Identity{UserID: 9, Roles: []string{"admin"}}, nil
		}
		return nil, errors.New("bad token")
	}
	invoices := map[int64]Invoice{1001: {ID: 1001, OwnerID: 1, Total: 4200}}
	auth := RequireUser(Bearer(verify))

	mux := http.NewServeMux()
	mux.Handle("GET /invoices/{id}", auth(InvoiceHandler{Load: func(id int64) (Invoice, bool) {
		inv, ok := invoices[id]
		return inv, ok
	}}))
	mux.Handle("GET /admin/stats", auth(RequireRole("admin")(http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) }))))
	return mux
}

func call(h http.Handler, path, token string) *httptest.ResponseRecorder {
	req := httptest.NewRequest("GET", path, nil)
	if token != "" {
		req.Header.Set("Authorization", "Bearer "+token)
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec
}

func TestAuthenticationAndAuthorization(t *testing.T) {
	h := routes()
	cases := []struct {
		name, path, token string
		want              int
	}{
		{"no credentials", "/invoices/1001", "", 401},
		{"bad token", "/invoices/1001", "forged", 401},
		{"owner", "/invoices/1001", "alice", 200},
		{"other user: IDOR blocked, same as missing", "/invoices/1001", "bob", 404},
		{"missing invoice", "/invoices/1002", "alice", 404},
		{"admin sees all", "/invoices/1001", "root", 200},
		{"role required", "/admin/stats", "alice", 403},
		{"role present", "/admin/stats", "root", 200},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			rec := call(h, c.path, c.token)
			if rec.Code != c.want {
				t.Fatalf("%s %s: %d, want %d", c.token, c.path, rec.Code, c.want)
			}
			if c.want == 401 && rec.Header().Get("WWW-Authenticate") == "" {
				t.Fatal("401 without WWW-Authenticate")
			}
		})
	}
}

func TestContextKeyCannotBeForged(t *testing.T) {
	type ctxKey struct{} // same name in another scope is a different type
	ctx := context.WithValue(t.Context(), ctxKey{}, &Identity{UserID: 1, Roles: []string{"admin"}})
	ctx = context.WithValue(ctx, "identity", &Identity{UserID: 1})
	if From(ctx) != nil {
		t.Fatal("identity forged with a foreign key")
	}
	if id := From(WithIdentity(ctx, &Identity{UserID: 2})); id == nil || id.UserID != 2 {
		t.Fatal("WithIdentity/From round trip failed")
	}
}

The adapters connect the two credential kinds of this chapter to RequireUser: SessionAuth reads what session.Store.Load attached, JWTVerifier wraps jwtauth.Issuer.Verify. The test runs one route with a cookie, a bearer token, a forged token and an anonymous session.

go
package authmw

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"academy/authentication-in-go/jwtauth"
	"academy/authentication-in-go/session"
)

// SessionAuth reads the session that session.Store.Load attached to the
// context. No cookie or an anonymous session means "no credentials", so the
// next authenticator is tried.
func SessionAuth(r *http.Request) (*Identity, error) {
	sess, ok := session.From(r.Context())
	if !ok || sess.UserID == 0 {
		return nil, ErrNoCredentials
	}
	return &Identity{UserID: sess.UserID, Method: "session"}, nil
}

// JWTVerifier turns a verified access token into an Identity. The subject
// is "user:<id>" as issued by jwtauth.Issuer.Issue.
func JWTVerifier(is *jwtauth.Issuer) func(token string) (*Identity, error) {
	return func(token string) (*Identity, error) {
		c, err := is.Verify(token)
		if err != nil {
			return nil, err
		}
		raw, ok := strings.CutPrefix(c.Subject, "user:")
		id, err := strconv.ParseInt(raw, 10, 64)
		if !ok || err != nil {
			return nil, fmt.Errorf("authmw: unexpected subject %q", c.Subject)
		}
		return &Identity{UserID: id, Roles: c.Roles}, nil
	}
}
go
package authmw

import (
	"crypto/ed25519"
	"crypto/rand"
	"net/http"
	"net/http/httptest"
	"strconv"
	"testing"
	"time"

	"academy/authentication-in-go/jwtauth"
	"academy/authentication-in-go/session"
)

// One API, two credential kinds: a browser with a session cookie and a
// mobile client with a bearer JWT, tried in that fixed order. A bad bearer
// token is a 401, never a fall-through to anonymous.
func TestSessionAndBearerOnOneRoute(t *testing.T) {
	store := session.NewStore(30*time.Minute, 12*time.Hour)
	_, priv, _ := ed25519.GenerateKey(rand.Reader)
	ring := jwtauth.NewKeyRing()
	ring.Add("k1", priv)
	is := &jwtauth.Issuer{Keys: ring, Issuer: "https://auth.example.test", Audience: "orders-api",
		TTL: 10 * time.Minute, Now: time.Now}

	me := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		id := From(r.Context())
		w.Write([]byte(id.Method + ":" + strconv.FormatInt(id.UserID, 10)))
	})
	h := store.Load(RequireUser(SessionAuth, Bearer(JWTVerifier(is)))(me))

	call := func(cookie, bearer string) *httptest.ResponseRecorder {
		req := httptest.NewRequest("GET", "/me", nil)
		if cookie != "" {
			req.AddCookie(&http.Cookie{Name: session.CookieName, Value: cookie})
		}
		if bearer != "" {
			req.Header.Set("Authorization", "Bearer "+bearer)
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		return rec
	}

	sid := store.Create(7)
	if rec := call(sid, ""); rec.Code != 200 || rec.Body.String() != "session:7" {
		t.Fatalf("cookie: %d %q", rec.Code, rec.Body)
	}
	tok, _ := is.Issue("user:8", "j1", nil)
	if rec := call("", tok); rec.Code != 200 || rec.Body.String() != "bearer:8" {
		t.Fatalf("bearer: %d %q", rec.Code, rec.Body)
	}
	if rec := call("", "forged.token.value"); rec.Code != 401 {
		t.Fatalf("forged bearer: %d", rec.Code)
	}
	anon := store.Create(0)
	if rec := call(anon, ""); rec.Code != 401 {
		t.Fatalf("anonymous session: %d", rec.Code)
	}
	if rec := call("", ""); rec.Code != 401 {
		t.Fatalf("nothing: %d", rec.Code)
	}
}

CSRF: double-submit cookie, SameSite, Origin check and http.CrossOriginProtection Must-know ​

In plain words: With cookie-based sessions, the browser attaches the cookie to every request to your site, even one triggered by a form on evil.example. CSRF defence is how your server tells "the user clicked Transfer on our page" from "another site made the user's browser post to us".

Common misunderstanding: "SameSite=Lax cookies solve CSRF." They stop most cross-site POSTs, but not requests from a sibling subdomain (same site, different origin: blog.example.test against bank.example.test), not state-changing GETs, and MDN notes that when Lax is only a browser default, "cookies are also included in POST requests, as long as they were set no more than two minutes before the request was made". Second: "the naive double-submit cookie is fine." OWASP marks it DISCOURAGED: it "is bypassable by an attacker who can write cookies on the target domain". Bind the token to the session.

Definition: OWASP's guidance: "Stateful software should use the synchronizer token pattern", "Stateless software should use double submit cookies", and the recommended variant is the signed double-submit cookie "which explicitly ties tokens to the user's authenticated session (e.g., session ID)" using HMAC with a server-side key. SameSite limits when the browser sends the cookie at all. The Origin check compares the Origin header of an unsafe request with your own origin or an allow-list. Fetch metadata: browsers send Sec-Fetch-Site: same-origin | same-site | cross-site | none. Go 1.25 http.CrossOriginProtection uses it: safe methods (GET, HEAD, OPTIONS) pass; Sec-Fetch-Site of same-origin or none passes; other values are rejected with 403 (cross-origin request detected from Sec-Fetch-Site header) unless the origin was added with AddTrustedOrigin or the route with AddInsecureBypassPattern; with no Sec-Fetch-Site, an Origin that does not match Host is rejected. OWASP: "Starting from 1.25, Go developers can rely on the built-in CrossOriginProtection type." The whole middleware is walked through in Middlewares.

     evil.example.test page                       bank.example.test (cookie: __Host-sid=Qz8..)
1    <form action=https://bank.../transfer method=POST> auto-submits
2    browser: SameSite=Lax -> cookie NOT sent on cross-site POST          (first wall)
3    cookie without SameSite: no Lax default (older browser), or the default-Lax 2-minute POST window -> cookie sent
4    Sec-Fetch-Site: cross-site -> CrossOriginProtection 403              (second wall)
5    no fetch metadata, Origin: https://evil.example.test != Host -> 403  (third wall)
6    no Origin at all -> token check: csrf_token missing or not HMAC(session) -> 403  (fourth wall)

Real scenario: a server-rendered admin panel with forms; a same-site marketing blog with an XSS that can send same-site requests to the app; an SPA on app.example.test calling api.example.test with cookies (AddTrustedOrigin); a payment webhook that must bypass CSRF because it has no browser and no cookie (AddInsecureBypassPattern("POST /webhooks/"), authenticated by a signature instead); a logout endpoint (also CSRF-protected, or anyone can log your users out).

DefenceStopsDoes not stopGo
SameSite=Lax (set explicitly)Cross-site POST, fetch, iframesSame-site attackers, state-changing GEThttp.Cookie.SameSite
No SameSite (browser applies Lax by default)As above in browsers that default to LaxAlso cross-site POSTs within two minutes of the cookie being set; browsers that do not default to LaxAlways set the attribute
SameSite=StrictAlso cross-site top-level GETSame-site attackers; breaks links from email into a logged-in pagehttp.SameSiteStrictMode
CrossOriginProtection (1.25)Cross-site and same-site-cross-origin unsafe requests in modern browsersOld browsers without Sec-Fetch-Site and without Originhttp.NewCrossOriginProtection()
Origin checkRequests with a foreign OriginRequests without Originr.Header.Get("Origin") vs r.Host
Synchronizer / signed double-submit tokenAny request without the session's tokenXSS on your own origin (it can read the token)HMAC token in form/header
Bearer tokens in AuthorizationCSRF entirely (browsers do not attach them)XSS stealing the token from storageauthmw.Bearer

Fix / how to use it: the csrf package has the session-bound HMAC token with an Origin check, and a //go:build go1.25 file that puts CrossOriginProtection in front.

go
// Package csrf protects cookie-authenticated, state-changing requests with a
// session-bound HMAC token (OWASP "signed double-submit cookie" / synchronizer
// token) plus an Origin check. Go 1.25+ code can add
// http.CrossOriginProtection in front (crossorigin.go).
package csrf

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"net/http"
	"net/url"
	"strings"
)

// Protector issues and checks tokens. Secret is 32 random bytes from a
// secret store; SessionID returns the current session's ID (or "" if none).
type Protector struct {
	Secret         []byte
	SessionID      func(r *http.Request) string
	TrustedOrigins map[string]bool // e.g. "https://app.example.test"
}

// Token returns nonce.mac where mac = HMAC-SHA256(secret, sessionID "!" nonce).
// Render it in a hidden form field or a meta tag for fetch().
func (p *Protector) Token(sessionID string) string {
	nonce := make([]byte, 16)
	rand.Read(nonce)
	n := base64.RawURLEncoding.EncodeToString(nonce)
	return n + "." + p.mac(sessionID, n)
}

func (p *Protector) mac(sessionID, nonce string) string {
	m := hmac.New(sha256.New, p.Secret)
	m.Write([]byte(sessionID + "!" + nonce))
	return base64.RawURLEncoding.EncodeToString(m.Sum(nil))
}

func (p *Protector) valid(sessionID, tok string) bool {
	nonce, mac, ok := strings.Cut(tok, ".")
	if !ok || sessionID == "" {
		return false
	}
	return hmac.Equal([]byte(mac), []byte(p.mac(sessionID, nonce))) // constant time
}

// originOK implements the OWASP "verify origin with standard headers" check:
// if Origin is present it must be our own host or a trusted origin.
func (p *Protector) originOK(r *http.Request) bool {
	o := r.Header.Get("Origin")
	if o == "" || o == "null" {
		return o == "" // no Origin: older browser or non-browser; rely on the token
	}
	if p.TrustedOrigins[o] {
		return true
	}
	u, err := url.Parse(o)
	return err == nil && u.Host == r.Host
}

// Middleware rejects unsafe methods without a valid token with 403.
func (p *Protector) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodGet, http.MethodHead, http.MethodOptions:
			next.ServeHTTP(w, r) // safe methods must not change state
			return
		}
		tok := r.Header.Get("X-CSRF-Token")
		if tok == "" {
			tok = r.PostFormValue("csrf_token")
		}
		if !p.originOK(r) || !p.valid(p.SessionID(r), tok) {
			http.Error(w, "forbidden: CSRF check failed", http.StatusForbidden)
			return
		}
		next.ServeHTTP(w, r)
	})
}
go
//go:build go1.25

package csrf

import "net/http"

// Fetch-metadata layer from the standard library (Go 1.25): rejects non-safe
// requests whose Sec-Fetch-Site is cross-site or same-site, or whose Origin
// does not match Host. It is tokenless; keep the token check for old
// browsers and for same-site-but-cross-origin threats you care about.
func WithCrossOriginProtection(next http.Handler, trusted ...string) (http.Handler, error) {
	cop := http.NewCrossOriginProtection()
	for _, o := range trusted {
		if err := cop.AddTrustedOrigin(o); err != nil {
			return nil, err
		}
	}
	return cop.Handler(next), nil
}
go
package csrf

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
)

func setup() (*Protector, http.Handler) {
	p := &Protector{
		Secret:    []byte("0123456789abcdef0123456789abcdef"),
		SessionID: func(r *http.Request) string { return r.Header.Get("X-Test-Session") },
	}
	h := p.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("transferred"))
	}))
	return p, h
}

func post(h http.Handler, session, token, origin string) int {
	form := url.Values{"csrf_token": {token}, "amount": {"100"}}
	req := httptest.NewRequest("POST", "https://bank.example.test/transfer", strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("X-Test-Session", session)
	if origin != "" {
		req.Header.Set("Origin", origin)
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec.Code
}

func TestTokenBoundToSession(t *testing.T) {
	p, h := setup()
	tok := p.Token("sess-A")
	if c := post(h, "sess-A", tok, "https://bank.example.test"); c != 200 {
		t.Fatalf("own form: %d", c)
	}
	if c := post(h, "sess-A", "", ""); c != 403 {
		t.Fatalf("missing token: %d", c)
	}
	// An attacker's own valid token does not work in the victim's session.
	if c := post(h, "sess-B", tok, ""); c != 403 {
		t.Fatalf("token from another session: %d", c)
	}
	if c := post(h, "sess-A", tok, "https://evil.example.test"); c != 403 {
		t.Fatalf("cross-origin with valid token: %d", c)
	}
}

func TestSafeMethodsPass(t *testing.T) {
	_, h := setup()
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest("GET", "/transfer", nil))
	if rec.Code != 200 {
		t.Fatalf("GET: %d", rec.Code)
	}
}
go
//go:build go1.25

package csrf

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestCrossOriginProtection(t *testing.T) {
	h, err := WithCrossOriginProtection(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}),
		"https://admin.example.test")
	if err != nil {
		t.Fatal(err)
	}
	cases := []struct {
		site, origin string
		want         int
	}{
		{"same-origin", "", 200},
		{"cross-site", "https://evil.example.test", 403},
		{"same-site", "https://blog.example.test", 403},
		{"", "https://evil.example.test", 403},            // old browser: Origin vs Host
		{"", "", 200},                                     // curl, server-to-server
		{"cross-site", "https://admin.example.test", 200}, // trusted origin
	}
	for _, c := range cases {
		req := httptest.NewRequest("POST", "https://bank.example.test/transfer", nil)
		if c.site != "" {
			req.Header.Set("Sec-Fetch-Site", c.site)
		}
		if c.origin != "" {
			req.Header.Set("Origin", c.origin)
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		if rec.Code != c.want {
			t.Errorf("Sec-Fetch-Site=%q Origin=%q: %d, want %d", c.site, c.origin, rec.Code, c.want)
		}
	}
}

Input sanitization vs validation vs output encoding Must-know ​

In plain words: Three different jobs. Validation checks input at the door and rejects what does not fit ("this is not an email"). Sanitization cleans HTML that you have decided to display as HTML (a rich-text bio). Output encoding happens at render time and turns data into text for the exact context it lands in (HTML body, attribute, URL, JavaScript). Most XSS bugs come from doing one and thinking it covers the others.

Common misunderstanding: "Strip < and > from all input and XSS is solved." It breaks legitimate data (a < b, names like O'Brien for quote-stripping), and it misses contexts where no angle bracket is needed (javascript: in an href, an unquoted attribute, a JavaScript string). OWASP's XSS cheat sheet starts from output encoding for each context: "start with your framework's default output encoding protection", and "Each variable used in the user interface should be passed through an output encoding function." Second: "html/template handles everything, so template.HTML(userBio) is fine." Converting to template.HTML tells the engine "this is already safe"; that conversion is exactly where sanitization must happen.

Definition: validation is an allow-list per field (type, length, format, range), done once at the boundary; in Go, net/mail.ParseAddress, regexp, strconv, utf8.RuneCountInString. Sanitization parses HTML and keeps only allowed elements and attributes: bluemonday "takes untrusted user generated content as an input, and will return HTML that has been sanitised against an allowlist of approved HTML elements and attributes"; bluemonday.UGCPolicy() "allows a broad selection of HTML elements and attributes that are safe for user generated content" (no script, iframe, style), StrictPolicy() strips all HTML. Output encoding in html/template: "HTML templates treat data values as plain text which should be encoded so they can be safely embedded in an HTML document. The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts." A disallowed URL scheme in an attribute becomes #ZgotmplZ. text/template does no escaping at all. Template mechanics (layouts, caching, forms) are in html/template.

username = "</script><script>alert(1)</script>", website = "javascript:alert(1)", bio = "<b>Go</b><script>..."
1  Validate      username fails ^[a-z0-9_-]{3,32}$ -> 400 at sign-up (in this test we render anyway)
2  SanitizeBio   bluemonday UGC: "<b>Go</b>" kept, <script>, onerror, javascript: removed
3  Render (real output, html/template):
   <h1>&lt;/script&gt;&lt;script&gt;alert(1)&lt;/script&gt;</h1>        HTML text context
   <a href="#ZgotmplZ">site</a>                                         URL attribute: scheme blocked
   <script>const user = "\u003c/script\u003e...";</script>              JS string context

Real scenario: a comment field rendered on a public page; a profile "website" link; a search box echoed back in the results page; an admin dashboard that renders JSON from the database into a <script> block; an email template built with text/template (no escaping: use html/template for HTML mail).

JobWhenGo toolFails if you skip it
ValidationAt input, before storingnet/mail, regexp, strconv, length checksGarbage in the database; weaker downstream assumptions
CanonicalizationAt inputstrings.ToLower email, Unicode normalizationDuplicate accounts (Alice@ vs alice@)
SanitizationOnly for fields rendered as HTMLbluemonday.UGCPolicy().SanitizeStored XSS through rich text
Output encodingAt render, every field, by contexthtml/template (contextual autoescaping)Reflected and stored XSS
SQL parametersAt query$1 placeholders (database/sql, pgx)SQL injection (sanitizing does not replace this)
Header valuesWhen echoing into headersReject CR/LFHeader injection

Fix / how to use it:

go
// Package sanitize separates three jobs that are often mixed up:
// validation (reject bad input at the edge), sanitization (clean HTML you
// intend to render as HTML), and output encoding (html/template escaping
// everything else at render time).
package sanitize

import (
	"errors"
	"html/template"
	"io"
	"net/mail"
	"regexp"
	"strings"
	"unicode/utf8"

	"github.com/microcosm-cc/bluemonday"
)

var (
	ErrEmail    = errors.New("email: not a valid address")
	ErrUsername = errors.New("username: 3-32 characters, a-z 0-9 _ -")
	ErrBio      = errors.New("bio: at most 2000 characters")
)

var usernameRE = regexp.MustCompile(`^[a-z0-9_-]{3,32}$`)

type Signup struct {
	Email    string
	Username string
	Bio      string // may contain a little HTML (bold, links)
}

// Validate rejects, it does not repair: an allow-list per field.
func (s *Signup) Validate() error {
	addr, err := mail.ParseAddress(s.Email)
	if err != nil || addr.Address != strings.TrimSpace(s.Email) || len(s.Email) > 254 {
		return ErrEmail
	}
	s.Email = strings.ToLower(addr.Address) // canonical form for lookups
	if !usernameRE.MatchString(s.Username) {
		return ErrUsername
	}
	if utf8.RuneCountInString(s.Bio) > 2000 {
		return ErrBio
	}
	return nil
}

// ugc is safe for concurrent use; build it once.
var ugc = bluemonday.UGCPolicy()

// SanitizeBio is only for the field you deliberately render as HTML.
// The result is wrapped in template.HTML so html/template will not escape it
// a second time: that type conversion is the trust decision, so it lives here.
func SanitizeBio(bio string) template.HTML {
	return template.HTML(ugc.Sanitize(bio))
}

var page = template.Must(template.New("profile").Parse(
	`<h1>{{.Username}}</h1><a href="{{.Website}}">site</a><div class="bio">{{.Bio}}</div>
<script>const user = {{.Username}};</script>`))

type Profile struct {
	Username string        // escaped for HTML, and for JS inside <script>
	Website  string        // escaped for a URL attribute; javascript: is neutralised
	Bio      template.HTML // already sanitized
}

func Render(w io.Writer, p Profile) error { return page.Execute(w, p) }
go
package sanitize

import (
	"errors"
	"strings"
	"testing"
)

func TestValidate(t *testing.T) {
	ok := Signup{Email: "Alice@Example.test", Username: "alice_1", Bio: "hi"}
	if err := ok.Validate(); err != nil || ok.Email != "alice@example.test" {
		t.Fatalf("%v %q", err, ok.Email)
	}
	bad := []struct {
		s    Signup
		want error
	}{
		{Signup{Email: "Alice <alice@example.test>", Username: "alice"}, ErrEmail},
		{Signup{Email: "not-an-email", Username: "alice"}, ErrEmail},
		{Signup{Email: "a@example.test", Username: "<script>"}, ErrUsername},
		{Signup{Email: "a@example.test", Username: "al"}, ErrUsername},
		{Signup{Email: "a@example.test", Username: "alice", Bio: strings.Repeat("x", 2001)}, ErrBio},
	}
	for _, c := range bad {
		if err := c.s.Validate(); !errors.Is(err, c.want) {
			t.Errorf("%+v: %v, want %v", c.s, err, c.want)
		}
	}
}

func TestSanitizeBio(t *testing.T) {
	got := string(SanitizeBio(`<b>Go</b> dev <script>alert(1)</script><a href="javascript:alert(1)">x</a><img src=x onerror=alert(1)>`))
	for _, bad := range []string{"<script", "javascript:", "onerror"} {
		if strings.Contains(got, bad) {
			t.Fatalf("sanitized bio still contains %q: %s", bad, got)
		}
	}
	if !strings.Contains(got, "<b>Go</b>") {
		t.Fatalf("allowed markup removed: %s", got)
	}
}

func TestOutputEncodingIsContextual(t *testing.T) {
	var b strings.Builder
	err := Render(&b, Profile{
		Username: `</script><script>alert(1)</script>`,
		Website:  `javascript:alert(1)`,
		Bio:      SanitizeBio(`<i>ok</i>`),
	})
	if err != nil {
		t.Fatal(err)
	}
	out := b.String()
	if strings.Contains(out, "<script>alert(1)") {
		t.Fatalf("username not escaped:\n%s", out)
	}
	if !strings.Contains(out, `href="#ZgotmplZ"`) {
		t.Fatalf("javascript: URL not neutralised:\n%s", out)
	}
	if !strings.Contains(out, "<i>ok</i>") {
		t.Fatalf("sanitized HTML double-escaped:\n%s", out)
	}
	if strings.Contains(out, `const user = "</script>`) || !strings.Contains(out, `u003c/script`) {
		t.Fatalf("JS context not escaped as a JS string:\n%s", out)
	}
}

Password reset flow: single-use token, hash stored, expiry, enumeration-safe responses Must-know ​

In plain words: "Forgot password" is a second login form that bypasses the password, so it must be as strong as the first. Answer the same thing for every email, send a random link only if the account exists, store only a hash of the token, let it work once and briefly, and after the reset end every existing session.

Common misunderstanding: "The reset link can log the user in directly, it is more convenient." OWASP: "Don't automatically log the user in, as this introduces additional complexity to the authentication and session handling code". Second: "store the token, it is random anyway." A read-only leak of the table (backup, replica) would then let the attacker reset any account with a pending request. Third: "build the link from the request's Host." OWASP: "Don't rely on the Host header while creating the reset URLs to avoid Host Header Injection attacks."

Definition: OWASP Forgot Password: "Return a consistent message for both existent and non-existent accounts", "Ensure that the time taken for the user response message is uniform", and tokens must be "Randomly generated using a cryptographically safe algorithm", "Sufficiently long to protect against brute-force attacks", "Stored securely", "Single use and expire after an appropriate period". After recovery, "invalidate existing sessions and outstanding password reset and recovery links or codes". In this module both branches of RequestReset generate and hash a token, scan the store and enqueue one job; only the job, off the request path, knows whether to send, and TestRequestResetSameStepsBothBranches counts the steps on both branches. The reset page should send Referrer-Policy: no-referrer so the token does not leak to third-party resources. Laravel's default broker uses 'expire' => 60 (minutes) and 'throttle' => 60 (seconds between requests).

1  POST /forgot-password email=alice@...      -> 200 "If an account exists for that address, ..."
   POST /forgot-password email=nobody@...     -> 200 "If an account exists for that address, ..." (same)
2  BOTH emails: raw = hex(32 random bytes), sha256(raw), scan the token store, enqueue ONE mail job
   alice only: store sha256(raw), user 1, purpose reset, expires +30 min (older tokens deleted);
   the queued job mails https://app.example.test/reset-password?token=raw, nobody's job sends nothing
3  GET /reset-password?token=raw              -> form (Referrer-Policy: no-referrer)
4  POST new password                          -> consume: look up sha256(raw) AND delete, same critical section
5  expired? -> 400 "invalid or expired link";  ok -> policy check, Argon2id, UPDATE users
6  end all sessions + refresh token families of user 1; send "your password was changed" mail
7  second POST with the same raw              -> 400 (deleted in step 4)
Password reset: same answer for everyone, token usable oncePOST /forgot-passwordemail, rate limited per IP + emailaccount exists?decided silently200 "If an account exists…"identical for both branchesyes (off the response path)token = 32 bytes from crypto/randstore sha256(token), user, purpose, expires = now + 30 mindelete older tokens; link from BaseURL config, never Host headeruser opens /reset-password?token=… (Referrer-Policy: no-referrer)consume: look up + deletein one transaction; thencheck expirypolicy check, Argon2id hashUPDATE users SETpassword_hash = …revoke every sessionand refresh token family;notify by email; no auto-loginEmail verification uses the same table with purpose = email_verification and a longer expiry.

Real scenario: an attacker scripting the forgot-password form to learn which emails have accounts; a reset token leaked through a Referer header to an analytics script; a link forwarded to the attacker in a support ticket and used before the user; a user who resets after a phishing incident while the attacker still holds a session (ended in step 6); two tabs submitting the same link at once (exactly one wins).

PropertyRuleThis moduleLaravel 13 Password broker
ResponseIdentical for existing and unknown emailreset.GenericPassword::sendResetLink returns a status slug per outcome: show one message for all of them
TokenCSPRNG, "sufficiently long" (use 128+ bits)256 bitsGenerated by the broker
StorageHash onlysha256(raw)database driver (a token table from the default users migration) or cache driver
LifetimeShort30 minexpire 60 min
Single useDelete on use, atomicallyconsume under the lockDeleted after reset
Rate limitPer email and IPlockout packagethrottle 60 s
After resetEnd sessions, revoke tokens, notifyEndSession callbackPasswordReset event
Link hostFrom configBaseURLAPP_URL

Fix / how to use it:

go
// Package reset implements single-use, expiring, hashed tokens for password
// reset and email verification, with responses that do not reveal whether
// an account exists.
package reset

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"strings"
	"sync"
	"sync/atomic"
	"time"
)

type Purpose string

const (
	PurposeReset  Purpose = "password_reset"
	PurposeVerify Purpose = "email_verification"
)

// Generic is the only answer the "forgot password" form ever gives.
const Generic = "If an account exists for that address, we have sent a link to reset the password."

var ErrInvalidToken = errors.New("reset: invalid or expired link")

type token struct {
	userID  int64
	purpose Purpose
	email   string // the address the link was sent to (verification binds to it)
	expires time.Time
}

// Users is the slice of the user repository this package needs.
type Users interface {
	IDByEmail(email string) (int64, bool)
	SetPassword(userID int64, plain string) error // hashes with Argon2id
	MarkVerified(userID int64) error
	EmailOf(userID int64) string // current address, to check a verification link still applies
}

type Service struct {
	Users      Users
	Send       func(email, link string) // the actual mail call, run inside a queued job
	Enqueue    func(job func())         // background queue; New runs jobs inline (tests)
	EndSession func(userID int64)       // session.Store.DestroyUser + refresh.RevokeUser
	BaseURL    string                   // from config, never from the Host header
	TTL        time.Duration            // 30 min for reset; 24 h is common for verification
	Now        func() time.Time

	Issued atomic.Int64 // tokens generated, for the uniform-work test

	mu     sync.Mutex
	byHash map[string]token // SHA-256(token) -> record
}

func New(u Users, send func(string, string), end func(int64), baseURL string) *Service {
	return &Service{Users: u, Send: send, EndSession: end, BaseURL: baseURL,
		Enqueue: func(job func()) { job() },
		TTL:     30 * time.Minute, Now: time.Now, byHash: map[string]token{}}
}

func digest(t string) string { s := sha256.Sum256([]byte(t)); return hex.EncodeToString(s[:]) }

// issue generates a token and, for a real user (userID != 0), stores only
// its hash. For an unknown address the same generation, hashing and store
// scan run, and nothing is stored: both branches cost the same.
func (s *Service) issue(userID int64, p Purpose, email string) string {
	b := make([]byte, 32)
	rand.Read(b)
	raw := hex.EncodeToString(b)
	h := digest(raw)
	s.Issued.Add(1)
	s.mu.Lock()
	for k, t := range s.byHash { // one live token per user and purpose
		if t.userID == userID && t.purpose == p {
			delete(s.byHash, k)
		}
	}
	if userID != 0 {
		s.byHash[h] = token{userID: userID, purpose: p, email: email, expires: s.Now().Add(s.TTL)}
	}
	s.mu.Unlock()
	return raw
}

// RequestReset always returns Generic and does the same work on the request
// path for known and unknown addresses: one token generated, one job
// enqueued. Only the job (off the request path) decides whether to mail.
func (s *Service) RequestReset(email string) string {
	email = strings.ToLower(strings.TrimSpace(email))
	id, ok := s.Users.IDByEmail(email)
	raw := s.issue(id, PurposeReset, email) // id is 0 when unknown
	link := s.BaseURL + "/reset-password?token=" + raw
	s.Enqueue(func() {
		if ok {
			s.Send(email, link)
		}
	})
	return Generic
}

// consume deletes the token in the same critical section that checks it, so
// two concurrent submissions cannot both succeed.
func (s *Service) consume(raw string, p Purpose) (token, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	h := digest(raw)
	t, ok := s.byHash[h]
	if !ok || t.purpose != p {
		return token{}, ErrInvalidToken
	}
	delete(s.byHash, h)
	if s.Now().After(t.expires) {
		return token{}, ErrInvalidToken
	}
	return t, nil
}

// ConfirmReset sets the new password and ends every session and refresh
// token of the user. It does not log the user in.
func (s *Service) ConfirmReset(raw, newPassword string) error {
	t, err := s.consume(raw, PurposeReset)
	if err != nil {
		return err
	}
	if err := s.Users.SetPassword(t.userID, newPassword); err != nil {
		return err
	}
	s.EndSession(t.userID)
	return nil
}

// SendVerification and ConfirmEmail reuse the same mechanism.
func (s *Service) SendVerification(userID int64, email string) {
	email = strings.ToLower(strings.TrimSpace(email))
	raw := s.issue(userID, PurposeVerify, email)
	link := s.BaseURL + "/verify-email?token=" + raw
	s.Enqueue(func() { s.Send(email, link) })
}

// ConfirmEmail verifies the address the link was sent to, and only if it is
// still the user's address: a link sent before an email change is void.
func (s *Service) ConfirmEmail(raw string) error {
	t, err := s.consume(raw, PurposeVerify)
	if err != nil {
		return err
	}
	if !strings.EqualFold(s.Users.EmailOf(t.userID), t.email) {
		return ErrInvalidToken
	}
	return s.Users.MarkVerified(t.userID)
}
go
package reset

import (
	"errors"
	"net/url"
	"strings"
	"sync"
	"testing"
	"time"
)

type fakeUsers struct {
	mu       sync.Mutex
	pw       map[int64]string
	verified map[int64]bool
	email    map[int64]string
}

func (f *fakeUsers) IDByEmail(e string) (int64, bool) {
	if e == "alice@example.test" {
		return 1, true
	}
	return 0, false
}
func (f *fakeUsers) SetPassword(id int64, p string) error {
	f.mu.Lock()
	f.pw[id] = p
	f.mu.Unlock()
	return nil
}
func (f *fakeUsers) MarkVerified(id int64) error { f.verified[id] = true; return nil }
func (f *fakeUsers) EmailOf(id int64) string     { return f.email[id] }

type outbox struct {
	mu    sync.Mutex
	links []string
}

func (o *outbox) send(_, link string) { o.mu.Lock(); o.links = append(o.links, link); o.mu.Unlock() }

func tokenFrom(t *testing.T, link string) string {
	u, err := url.Parse(link)
	if err != nil {
		t.Fatal(err)
	}
	return u.Query().Get("token")
}

func newSvc() (*Service, *fakeUsers, *outbox, *[]int64) {
	u := &fakeUsers{pw: map[int64]string{}, verified: map[int64]bool{}, email: map[int64]string{1: "alice@example.test"}}
	o := &outbox{}
	ended := &[]int64{}
	s := New(u, o.send, func(id int64) { *ended = append(*ended, id) }, "https://app.example.test")
	return s, u, o, ended
}

func TestEnumerationSafeResponse(t *testing.T) {
	s, _, o, _ := newSvc()
	a := s.RequestReset("Alice@Example.test ")
	b := s.RequestReset("nobody@example.test")
	if a != b || a != Generic {
		t.Fatalf("responses differ: %q vs %q", a, b)
	}
	if len(o.links) != 1 || !strings.HasPrefix(o.links[0], "https://app.example.test/reset-password?token=") {
		t.Fatalf("links: %v", o.links)
	}
}

func TestSingleUseHashedAndSessionsEnded(t *testing.T) {
	s, u, o, ended := newSvc()
	s.RequestReset("alice@example.test")
	raw := tokenFrom(t, o.links[0])
	for k := range s.byHash {
		if k == raw {
			t.Fatal("raw token stored")
		}
	}
	if err := s.ConfirmReset(raw, "a brand new long passphrase"); err != nil {
		t.Fatal(err)
	}
	if u.pw[1] != "a brand new long passphrase" || len(*ended) != 1 {
		t.Fatalf("password %q, sessions ended %v", u.pw[1], *ended)
	}
	if err := s.ConfirmReset(raw, "second use"); !errors.Is(err, ErrInvalidToken) {
		t.Fatalf("second use: %v", err)
	}
}

func TestExpiryAndNewerTokenWins(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	s, _, o, _ := newSvc()
	s.Now = func() time.Time { return now }
	s.RequestReset("alice@example.test")
	s.RequestReset("alice@example.test")
	first, second := tokenFrom(t, o.links[0]), tokenFrom(t, o.links[1])
	if err := s.ConfirmReset(first, "x"); !errors.Is(err, ErrInvalidToken) {
		t.Fatal("older link still valid after a newer one was sent")
	}
	now = now.Add(31 * time.Minute)
	if err := s.ConfirmReset(second, "x"); !errors.Is(err, ErrInvalidToken) {
		t.Fatal("expired link accepted")
	}
}

func TestConcurrentConfirmHasOneWinner(t *testing.T) {
	s, _, o, _ := newSvc()
	s.RequestReset("alice@example.test")
	raw := tokenFrom(t, o.links[0])
	var wg sync.WaitGroup
	var mu sync.Mutex
	wins := 0
	for range 10 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if s.ConfirmReset(raw, "concurrent passphrase") == nil {
				mu.Lock()
				wins++
				mu.Unlock()
			}
		}()
	}
	wg.Wait()
	if wins != 1 {
		t.Fatalf("%d winners", wins)
	}
}

func TestEmailVerificationPurposeIsSeparate(t *testing.T) {
	s, u, o, _ := newSvc()
	s.SendVerification(1, "alice@example.test")
	raw := tokenFrom(t, o.links[0])
	if err := s.ConfirmReset(raw, "x"); !errors.Is(err, ErrInvalidToken) {
		t.Fatal("verification token accepted as a reset token")
	}
	s.SendVerification(1, "alice@example.test")
	if err := s.ConfirmEmail(tokenFrom(t, o.links[1])); err != nil || !u.verified[1] {
		t.Fatalf("verify: %v", err)
	}
}
go
package reset

import (
	"errors"
	"testing"
)

// The verification link proves control of the address it was sent to. If
// the user changed the address meanwhile, the old link must not verify.
func TestVerificationBoundToAddress(t *testing.T) {
	s, u, o, _ := newSvc()
	u.email = map[int64]string{1: "alice@example.test"}
	s.SendVerification(1, "alice@example.test")
	oldLink := tokenFrom(t, o.links[0])
	u.email[1] = "alice@new.example.test" // address changed after the mail went out
	if err := s.ConfirmEmail(oldLink); !errors.Is(err, ErrInvalidToken) {
		t.Fatalf("old-address token verified the new address: err=%v verified=%v", err, u.verified[1])
	}
	if u.verified[1] {
		t.Fatal("marked verified")
	}
	s.SendVerification(1, "alice@new.example.test")
	if err := s.ConfirmEmail(tokenFrom(t, o.links[1])); err != nil || !u.verified[1] {
		t.Fatalf("new address: %v", err)
	}
}

// Both branches of RequestReset must do the same work on the request path:
// one token generated and one mail job enqueued; only the job decides
// whether a mail is actually sent.
func TestRequestResetSameStepsBothBranches(t *testing.T) {
	s, _, _, _ := newSvc()
	var jobs int
	s.Enqueue = func(job func()) { jobs++; job() }
	s.RequestReset("alice@example.test")
	known, knownJobs := s.Issued.Load(), jobs
	s.RequestReset("nobody@example.test")
	if got := s.Issued.Load() - known; got != known {
		t.Fatalf("tokens generated: known=%d unknown=%d", known, got)
	}
	if jobs-knownJobs != knownJobs {
		t.Fatalf("jobs enqueued: known=%d unknown=%d", knownJobs, jobs-knownJobs)
	}
}

Email verification Important ​

In plain words: Prove that the person who signed up controls the address before you trust it for password resets, notifications or "log in with email". It is the same token machinery as password reset with a different purpose and a longer expiry.

Common misunderstanding: "A verification link can be reused, it only flips a flag." A verification token that also logs the user in is a login token and needs the same care. And a token for one purpose must not work for another: the test proves a verification token is rejected by the reset endpoint.

Definition: a verification token is random, hashed in storage, bound to (user, purpose, email address), single use, and typically valid for hours. When the user changes their email, the new address gets its own token and the old address gets a notification. OIDC providers expose email_verified in the ID token for the same purpose.

1  sign-up alice@example.test -> user 1, email_verified = false
2  SendVerification(1, email) -> sha256(raw), purpose email_verification, expires +24 h
3  click link -> ConfirmEmail(raw) -> consume (purpose must match) -> MarkVerified(1)
4  same raw used on /reset-password -> rejected: purpose mismatch

Real scenario: a marketplace that must not send payouts to an unverified email; an account takeover where the attacker signs up first with the victim's address (verification stops it from being usable); an email change on an existing account; "magic link" login (a verification-style token that grants a session: short expiry, single use, rotate the session).

Token kindPurpose fieldTypical expiryGrants a session?
Password resetpassword_reset30-60 minNo (user logs in afterwards)
Email verificationemail_verification24 hNo
Email change confirmemail_change1-24 hNo
Magic link loginlogin10-15 minYes: rotate session, treat as a password

Fix / how to use it: reuse the reset machinery with its own purpose: reset.Service.SendVerification at sign-up and on email change, ConfirmEmail on the link. The token record stores the address the link was sent to, and ConfirmEmail marks the user verified only if that is still the user's address (Users.EmailOf), so a link mailed before an email change is void. TestEmailVerificationPurposeIsSeparate and TestVerificationBoundToAddress (in the reset test files above) prove a verification token is rejected by the reset endpoint and by a changed address. Gate sensitive actions on email_verified, not on the mere existence of the account.

Account lockout and rate limiting Important ​

In plain words: Slow down repeated failures for one account (someone guessing alice's password) and repeated attempts from one source (someone trying a leaked password list against many accounts), without letting an attacker lock real users out on purpose.

Common misunderstanding: "Lock the account for 24 hours after five failures." That gives every attacker a button to lock out any user (OWASP: care must be taken "to prevent it from being used to cause a denial of service by locking out other users' accounts"). Prefer an exponential delay that resets on success. Second: "throttle by IP only." OWASP: "The counter of failed logins should be associated with the account itself, rather than the source IP address", because botnets rotate IPs; and per-IP limits are still needed for credential stuffing that tries one password per account. Third: "only throttle real accounts." Then the 429 itself tells the attacker which emails exist; key the counter on what was typed.

Definition: account lockout here is a per-identifier delay: after Free failures, wait Base doubled per further failure, capped at Max (OWASP describes "an exponential lockout, where the lockout duration starts as a very short period (e.g., one second), but doubles after each failed login attempt"). Rate limiting per client IP is a token bucket (rate.NewLimiter(rate.Every(2*time.Second), 20) from golang.org/x/time/rate; algorithms in Rate Limiting in Go). NIST SP 800-63B-4 sets an upper bound: limit consecutive failures "to no more than 100", and suggests waits that grow "(e.g., 30 seconds up to an hour)". Answer 429 Too Many Requests with Retry-After.

alice@example.test, attempts from rotating IPs
1-5   fail, fail, fail, fail, fail        no delay (Free = 5)
6     fail                                -> wait 1 s
7,8   fail, fail                          -> wait 2 s, then 4 s
...   30 more failures                    -> capped at 15 min (never permanent)
ok    correct password after the wait     -> counter cleared
one IP, 100 different accounts            -> 20 allowed (burst), then 1 per 2 s

Real scenario: credential stuffing with a 2-million-line combo list from another site's breach; a targeted guess at the CEO's account; a customer who forgot whether they use the work or personal password and fails six times; a corporate NAT where 2,000 employees share one IP (set the per-IP burst accordingly, or key on IP + account).

ControlKeyed onStopsRisk
Exponential delayNormalised identifier (exists or not)Targeted guessingMild DoS, capped by Max
Hard lockoutAccountTargeted guessingDeliberate lockouts of real users
Token bucketClient IPStuffing from few IPsNAT false positives
Breached-password checkPasswordReuse of leaked passwordsBlocklist upkeep
CAPTCHA after N failuresSession/IPBotsSolvable by services; UX cost
MFAAccountAlmost all password attacksEnrolment and recovery effort

Fix / how to use it:

go
// Package lockout throttles login attempts two ways: per account identifier
// (exponential delay after a few failures, keyed on what was typed, whether
// or not the account exists) and per client IP (token bucket from
// golang.org/x/time/rate) against credential stuffing across many accounts.
package lockout

import (
	"strings"
	"sync"
	"time"

	"golang.org/x/time/rate"
)

type entry struct {
	failures int
	until    time.Time
}

type Guard struct {
	Free     int           // failures allowed before delays start, e.g. 5
	Base     time.Duration // first delay, e.g. 1 s; doubles per further failure
	Max      time.Duration // cap, e.g. 15 min: a delay, never a permanent lock
	PerIP    rate.Limit    // e.g. rate.Every(2 * time.Second)
	IPBurst  int           // e.g. 20
	Now      func() time.Time
	mu       sync.Mutex
	accounts map[string]*entry
	ips      map[string]*rate.Limiter
}

func New() *Guard {
	return &Guard{Free: 5, Base: time.Second, Max: 15 * time.Minute,
		PerIP: rate.Every(2 * time.Second), IPBurst: 20, Now: time.Now,
		accounts: map[string]*entry{}, ips: map[string]*rate.Limiter{}}
}

func norm(id string) string { return strings.ToLower(strings.TrimSpace(id)) }

// Allow returns 0 if the attempt may proceed, or how long to wait (for a
// 429 with Retry-After). Call it before verifying the password.
func (g *Guard) Allow(account, ip string) time.Duration {
	g.mu.Lock()
	defer g.mu.Unlock()
	now := g.Now()
	if e := g.accounts[norm(account)]; e != nil && now.Before(e.until) {
		return e.until.Sub(now)
	}
	lim := g.ips[ip]
	if lim == nil {
		lim = rate.NewLimiter(g.PerIP, g.IPBurst)
		g.ips[ip] = lim
	}
	r := lim.ReserveN(now, 1)
	if d := r.DelayFrom(now); d > 0 {
		r.CancelAt(now)
		return d
	}
	return 0
}

// Fail records a failed attempt for the identifier.
func (g *Guard) Fail(account string) {
	g.mu.Lock()
	defer g.mu.Unlock()
	k := norm(account)
	e := g.accounts[k]
	if e == nil {
		e = &entry{}
		g.accounts[k] = e
	}
	e.failures++
	if n := e.failures - g.Free; n > 0 {
		d := g.Base << min(n-1, 20)
		e.until = g.Now().Add(min(d, g.Max))
	}
}

// Succeed clears the account counter.
func (g *Guard) Succeed(account string) {
	g.mu.Lock()
	delete(g.accounts, norm(account))
	g.mu.Unlock()
}
go
package lockout

import (
	"fmt"
	"testing"
	"time"
)

func TestExponentialDelayPerAccount(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	g := New()
	g.Now = func() time.Time { return now }
	for i := range 5 {
		if d := g.Allow("alice@example.test", fmt.Sprintf("10.0.0.%d", i)); d != 0 {
			t.Fatalf("attempt %d delayed %v", i, d)
		}
		g.Fail("alice@example.test")
	}
	g.Fail("Alice@Example.test") // 6th failure: 1 s
	if d := g.Allow("alice@example.test", "10.0.1.1"); d != time.Second {
		t.Fatalf("after 6 failures: %v", d)
	}
	now = now.Add(time.Second)
	g.Fail("alice@example.test") // 7th: 2 s
	g.Fail("alice@example.test") // 8th: 4 s
	if d := g.Allow("alice@example.test", "10.0.1.2"); d != 4*time.Second {
		t.Fatalf("after 8 failures: %v", d)
	}
	for range 30 {
		g.Fail("alice@example.test")
	}
	if d := g.Allow("alice@example.test", "10.0.1.3"); d != 15*time.Minute {
		t.Fatalf("cap: %v", d)
	}
	g.Succeed("alice@example.test")
	if d := g.Allow("alice@example.test", "10.0.1.4"); d != 0 {
		t.Fatalf("after success: %v", d)
	}
}

func TestUnknownAccountsAreThrottledToo(t *testing.T) {
	g := New()
	for range 6 {
		g.Fail("nobody@example.test") // the account does not exist
	}
	if d := g.Allow("nobody@example.test", "10.0.0.9"); d == 0 {
		t.Fatal("non-existent account not throttled: that difference leaks existence")
	}
}

func TestPerIPBucketStopsStuffing(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	g := New()
	g.Now = func() time.Time { return now }
	allowed := 0
	for i := range 100 { // 100 different accounts from one IP
		if g.Allow(fmt.Sprintf("user%d@example.test", i), "203.0.113.7") == 0 {
			allowed++
		}
	}
	if allowed != 20 {
		t.Fatalf("burst allowed %d, want 20", allowed)
	}
	if g.Allow("x@example.test", "198.51.100.1") != 0 {
		t.Fatal("another IP was throttled")
	}
}

MFA with TOTP: pquerna/otp and RFC 6238 Important ​

In plain words: The user's phone and your server share a secret. Every 30 seconds both compute a 6-digit code from the secret and the current time; if the user types the code your server computes, they have the phone. Combined with the password, a stolen password alone is no longer enough.

Common misunderstanding: "totp.Validate is all you need." It accepts the code for the current step and one step on either side, and it keeps no state: the same code works again within that window. RFC 6238: "The verifier MUST NOT accept the second attempt of the OTP after the successful validation has been issued for the first OTP". Track the last accepted time step per user. Second: "TOTP stops phishing." A real-time phishing proxy relays the code within its 30 seconds; only origin-bound credentials (passkeys) stop that.

Definition: RFC 6238: TOTP is HOTP (RFC 4226) with the counter T = floor((now - T0) / X), where X is the time step: "We RECOMMEND a default time-step size of 30 seconds"; "We RECOMMEND that at most one time step is allowed as the network delay." pquerna/otp/totp: Generate(GenerateOpts{Issuer, AccountName}) returns a key with Secret() (base32), URL() (otpauth://totp/... for the QR code) and Image(); Validate(passcode, secret) uses Period 30 and Skew 1; ValidateCustom and GenerateCodeCustom take ValidateOpts{Period, Skew, Digits, Algorithm}. The README's enrolment steps: generate, display, "Test that the user can successfully use their TOTP", store, and "Provide the user with 'recovery codes'". Recovery codes here come from crypto/rand.Text() (Go 1.24), which "contains at least 128 bits of randomness", so storing their SHA-256 is enough (NIST requires a password hashing scheme only for lookup secrets shorter than 112 bits).

secret S shared at enrolment (QR code: otpauth://totp/Academy:alice@example.test?secret=...&issuer=Academy)
1  09:00:10  phone: HOTP(S, 1795856410/30 = 59861880) = 492039 (illustrative); user types it
2  server    counters 59861880±1 -> match at 59861880 > last(0) -> accept, last = 59861880
3  09:00:15  same 492039 again (phished, replayed) -> match at 59861880 <= last -> reject
4  09:00:45  code from step 59861880 still in skew window, but already used -> reject
5  09:01:00  new step 59861882 -> new code -> accept

Real scenario: staff accounts on an admin panel that must use MFA (and may then have 8-character passwords per NIST); a user who lost their phone and uses a recovery code; an attacker with a phished password stopped at the TOTP prompt; a step-up check ("enter your code to change payout details").

FactorPhishing-resistantShared secret on serverGo package
SMS OTPNoCode in transitProvider SDK
Email OTPNoCode in transitnet/smtp or provider
TOTP (RFC 6238)NoYes (encrypt at rest)github.com/pquerna/otp/totp
Recovery codesNoHashes onlycrypto/rand.Text + SHA-256
Passkeys / WebAuthnYes (origin-bound)No (public key only)github.com/go-webauthn/webauthn

Fix / how to use it:

go
// Package mfa adds TOTP (RFC 6238) as a second factor with
// github.com/pquerna/otp, plus the replay check the RFC requires and
// hashed single-use recovery codes.
package mfa

import (
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/hex"
	"sync"
	"time"

	"github.com/pquerna/otp"
	"github.com/pquerna/otp/totp"
)

// Opts are the RFC 6238 defaults every authenticator app understands:
// 30-second step, 6 digits, HMAC-SHA1, one step of skew either way.
var Opts = totp.ValidateOpts{Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1}

// Enroll creates a secret and the otpauth:// URL to show as a QR code.
// Store key.Secret() encrypted at rest; activate only after Verify succeeds once.
func Enroll(issuer, account string) (*otp.Key, error) {
	return totp.Generate(totp.GenerateOpts{Issuer: issuer, AccountName: account})
}

// Verifier remembers the last accepted time step per user. totp.Validate
// alone accepts the same code again inside its window; RFC 6238 says the
// verifier "MUST NOT accept the second attempt of the OTP after the
// successful validation has been issued for the first OTP".
type Verifier struct {
	mu   sync.Mutex
	last map[int64]int64 // userID -> last accepted counter
}

func NewVerifier() *Verifier { return &Verifier{last: map[int64]int64{}} }

func (v *Verifier) Verify(userID int64, secret, code string, now time.Time) bool {
	step := int64(Opts.Period)
	counter := now.Unix() / step
	v.mu.Lock()
	defer v.mu.Unlock()
	for off := -int64(Opts.Skew); off <= int64(Opts.Skew); off++ {
		c := counter + off
		want, err := totp.GenerateCodeCustom(secret, time.Unix(c*step, 0), Opts)
		if err != nil {
			return false
		}
		if subtle.ConstantTimeCompare([]byte(want), []byte(code)) == 1 {
			if c <= v.last[userID] {
				return false // replayed or older than the last accepted code
			}
			v.last[userID] = c
			return true
		}
	}
	return false
}

// RecoveryCodes returns n codes for the user to print and their SHA-256
// hashes to store. rand.Text (Go 1.24) gives 26 base32 characters, at least
// 128 bits, so a fast hash is enough; a short code would need a password hash.
func RecoveryCodes(n int) (plain, hashes []string) {
	for range n {
		c := rand.Text()
		plain = append(plain, c)
		hashes = append(hashes, hashCode(c))
	}
	return plain, hashes
}

func hashCode(c string) string { s := sha256.Sum256([]byte(c)); return hex.EncodeToString(s[:]) }

// UseRecoveryCode removes the matching hash (single use) and reports success.
func UseRecoveryCode(stored []string, code string) ([]string, bool) {
	h := hashCode(code)
	for i, s := range stored {
		if subtle.ConstantTimeCompare([]byte(s), []byte(h)) == 1 {
			return append(stored[:i:i], stored[i+1:]...), true
		}
	}
	return stored, false
}
go
package mfa

import (
	"strings"
	"testing"
	"time"

	"github.com/pquerna/otp/totp"
)

func TestEnrollAndVerify(t *testing.T) {
	key, err := Enroll("Academy", "alice@example.test")
	if err != nil {
		t.Fatal(err)
	}
	if !strings.HasPrefix(key.URL(), "otpauth://totp/Academy:alice@example.test?") {
		t.Fatalf("url %s", key.URL())
	}
	now := time.Date(2026, 11, 28, 9, 0, 10, 0, time.UTC)
	code, _ := totp.GenerateCodeCustom(key.Secret(), now, Opts)

	v := NewVerifier()
	if !v.Verify(1, key.Secret(), code, now) {
		t.Fatal("valid code rejected")
	}
	if v.Verify(1, key.Secret(), code, now.Add(5*time.Second)) {
		t.Fatal("same code accepted twice: replay")
	}
	// The library alone would have accepted the replay:
	if ok, _ := totp.ValidateCustom(code, key.Secret(), now.Add(5*time.Second), Opts); !ok {
		t.Fatal("expected pquerna/otp to accept it (no replay state)")
	}
}

func TestSkewWindow(t *testing.T) {
	key, _ := Enroll("Academy", "bob@example.test")
	issued := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	code, _ := totp.GenerateCodeCustom(key.Secret(), issued, Opts)
	if !NewVerifier().Verify(2, key.Secret(), code, issued.Add(45*time.Second)) {
		t.Fatal("code from the previous step rejected (skew 1)")
	}
	if NewVerifier().Verify(2, key.Secret(), code, issued.Add(95*time.Second)) {
		t.Fatal("code three steps old accepted")
	}
}

func TestRecoveryCodesSingleUse(t *testing.T) {
	plain, stored := RecoveryCodes(10)
	if len(plain) != 10 || len(plain[0]) != 26 {
		t.Fatalf("codes %v", plain)
	}
	stored, ok := UseRecoveryCode(stored, plain[3])
	if !ok || len(stored) != 9 {
		t.Fatal("valid recovery code rejected")
	}
	if _, ok := UseRecoveryCode(stored, plain[3]); ok {
		t.Fatal("recovery code used twice")
	}
}

Passkeys and WebAuthn: go-webauthn (pointer) Good to know ​

In plain words: A passkey is a key pair created by the user's device for your site. Your server stores only the public key; at login the device signs a challenge after the user unlocks it with a fingerprint, face or PIN. There is no shared secret to phish, reuse or leak.

Common misunderstanding: "Passkeys are just another 2FA code." They can replace the password entirely (passwordless) or be a second factor, and the browser binds them to your origin, so a look-alike domain cannot use them. Another one: "the library handles storage." go-webauthn gives you the ceremonies; you store credentials (ID, public key, sign count, flags) per user, partitioned by Relying Party ID, as its README stresses ("credentials MUST be partitioned by Relying Party ID").

Definition: github.com/go-webauthn/webauthn/webauthn: webauthn.New(&webauthn.Config{RPID, RPDisplayName, RPOrigins}) ("At minimum, RPID and RPOrigins must be configured"), then two ceremonies, each in two steps: BeginRegistration(user) / FinishRegistration(user, session, r) and BeginLogin(user) / FinishLogin(user, session, r), plus BeginDiscoverableLogin / FinishDiscoverableLogin(handler, session, r) for usernameless login. The SessionData returned by Begin* must be kept server-side (in the pre-login session) until Finish*. The W3C spec is Web Authentication Level 3.

1  BeginLogin(user)  -> challenge (random), allowed credential ids; SessionData into session
2  browser: navigator.credentials.get(...) -> device asks for fingerprint -> signs challenge for RPID
3  FinishLogin(user, SessionData, r) -> verify signature with stored public key, origin, RPID, sign count
4  ok -> Rotate session (it is a login), update stored sign count and flags

Real scenario: a consumer app offering "Sign in with a passkey" next to the password form; an admin panel that requires a hardware security key (AAL3 territory); account recovery that still needs a careful non-passkey path.

NeedCall
Configure the relying partywebauthn.New(&webauthn.Config{RPID: "example.test", RPDisplayName: "Academy", RPOrigins: []string{"https://example.test"}})
Register a passkeyBeginRegistration(user), then FinishRegistration(user, session, r)
Log in (username first)BeginLogin(user), then FinishLogin(user, session, r)
Log in (usernameless)BeginDiscoverableLogin(), then FinishDiscoverableLogin(handler, session, r) (or FinishPasskeyLogin)
StoreCredential ID, public key, sign count, flags, per RPID

Fix / how to use it: store BeginRegistration/BeginLogin session data server-side in the pre-login session, call the matching Finish* with the same SessionData, persist the credential and update its sign count on every login, and rotate the session on success. Offer passkeys alongside the password at first, keep a recovery path that is at least as strong, and require them for admin accounts.

Secure logout Important ​

In plain words: Logout must end the session on the server. Deleting the cookie in the browser is a courtesy; the session record is what an attacker with a copied cookie would use.

Common misunderstanding: "Logout is a GET link." A GET logout can be triggered by any <img src> on another site, and it is not CSRF-protected. Make it a POST behind the CSRF check. Second: "logout revokes my JWT." It revokes nothing unless you delete the refresh token family and, if the access token must die now, denylist its jti.

Definition: secure logout = delete the server-side session (Store.Destroy), send an expiring cookie (MaxAge: -1 serialises as Max-Age=0), optionally Clear-Site-Data: "cache", "cookies", "storage" to wipe browser state, revoke the refresh token family for token-based clients, and offer "log out everywhere" (DestroyUser, RevokeUser). OWASP asks for a logout button "reachable from every web application resource and page".

1  POST /logout (cookie Qz8.., csrf_token ok)
2  Store.Destroy(Qz8..)                      server-side record gone
3  Set-Cookie: __Host-sid=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax
4  Clear-Site-Data: "cache", "cookies", "storage"
5  copied cookie Qz8.. replayed later -> Get: not found -> 401

Real scenario: a shared computer in a library; a stolen laptop reported to support ("log out all sessions"); an employee offboarded mid-session; a password change that should keep the current session but end all others (rotate the current one, destroy the rest).

Client typeWhat logout must do
Browser + server sessionDestroy session, expire cookie, Clear-Site-Data
SPA with refresh token in cookieRevoke refresh family, expire cookie; access token dies at exp
Mobile app with tokensRevoke refresh family; app deletes tokens from the keychain
OIDC loginLocal logout first; optionally RP-initiated logout at the provider
"Log out everywhere"DestroyUser + RevokeUser, optionally per-user "not before" for JWTs

Fix / how to use it: after.Server.Logout destroys the server-side session, sends ClearCookie() and Clear-Site-Data, and TestLoginRotatesAndSetsFlags proves the old cookie is rejected afterwards; token clients call refresh.Store.RevokeUser (and denylist the current jti if needed). Mount logout as POST behind the CSRF layer.

Mechanics ​

The request pipeline, in order Must-know ​

Order decides what each layer can rely on. This is the stack the chapter's packages assume, outermost first (the general ordering rules are in Middlewares):

1  recover, request id, logging              (Middlewares chapter)
2  http.CrossOriginProtection (Go 1.25)      reject cross-origin unsafe requests before any work
3  session.Store.Load                         cookie -> sha256 -> Session in ctx (never rejects)
4  csrf.Protector.Middleware                  unsafe methods need HMAC(session) token + Origin check
5  lockout.Guard (login routes only)          429 + Retry-After before hashing
6  authmw.RequireUser(SessionAuth, Bearer(JWTVerifier(is)))   401 if nobody; Identity in ctx
7  authmw.RequireRole("admin") (route group)  403
8  handler: load object, check owner/tenant  404 / 403, then do the work

Exact cookies and headers Must-know ​

Real Set-Cookie lines from the tests (Go 1.27.4 net/http):

session.Cookie(id)       __Host-sid=<id>; Path=/; HttpOnly; Secure; SameSite=Lax
session.ClearCookie()    __Host-sid=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax
before (no flags)        sid=1001
scs v2.9.0 configured    __Host-session=<token>; Path=/; HttpOnly; Secure; SameSite=Lax   (Persist=false: no Expires)
AttributeEffectGo fieldIf missing
HttpOnlyNot readable from document.cookieHttpOnly: trueXSS reads the session ID
SecureSent only over HTTPSSecure: trueSent in clear on any http:// request
SameSite=LaxNot sent on cross-site POST/fetch/iframeSameSite: http.SameSiteLaxModeBrowser default: Lax in some browsers, then with the 2-minute POST exception that an explicit Lax does not have
Path=/Whole sitePath: "/"Defaults to the request path's directory
no DomainHost-only cookieleave Domain emptySent to every subdomain
__Host- prefixBrowser enforces the three aboveName: "__Host-sid"A subdomain can toss a cookie with the same name
Max-Age / ExpiresPersistent cookieMaxAge, ExpiresSession cookie (deleted when the browser decides)
PartitionedCHIPS partitioned storagePartitioned: true (Go 1.23)Third-party context behaviour differs

Response headers the auth endpoints set: Cache-Control: no-store on login and pages with personal data, WWW-Authenticate: Bearer realm="api" with every 401, Retry-After: <seconds> with 429, Referrer-Policy: no-referrer on the reset page, and Clear-Site-Data: "cache", "cookies", "storage" on logout.

Error texts, verbatim Must-know ​

Real output (Go 1.27.4, the pinned module versions), except the ErrNoCookie row, which is read from net/http/request.go:

TextWhere it comes from
bcrypt: password length exceeds 72 bytesbcrypt.ErrPasswordTooLong from GenerateFromPassword
crypto/bcrypt: cost 32 is outside allowed inclusive range 4..31bcrypt.InvalidCostError
crypto/bcrypt: hashedPassword is not the hash of the given passwordbcrypt.ErrMismatchedHashAndPassword
password: hash is not in the expected PHC formatpassword.ErrInvalidHash (this module)
token has invalid claims: token is expiredgolang-jwt v5, errors.Is(err, jwt.ErrTokenExpired)
token has invalid claims: token has invalid audiencejwt.ErrTokenInvalidAudience
token has invalid claims: token has invalid issuerjwt.ErrTokenInvalidIssuer
token signature is invalid: signing method HS256 is invalidWithValidMethods rejecting alg confusion (jwt.ErrTokenSignatureInvalid)
token signature is invalid: signing method none is invalidSame, for "alg":"none"
token is malformed: token contains an invalid number of segmentsjwt.ErrTokenMalformed
token is unverifiable: error while executing keyfunc: unknown kid "k1"Keyfunc error (retired key) wrapped in jwt.ErrTokenUnverifiable
cross-origin request detected from Sec-Fetch-Site headerhttp.CrossOriginProtection, 403
cross-origin request detected, and/or browser is out of date: Sec-Fetch-Site is missing, and Origin does not match HostSame, old-browser path
http: named cookie not presenthttp.ErrNoCookie from r.Cookie(name) (from the source, not this run)
#ZgotmplZ in the outputhtml/template replaced an unsafe value in a URL or CSS context

Data model Important ​

The in-memory stores in the snippets map one-to-one onto these PostgreSQL tables. Every secret that a client presents (session ID, refresh token, reset token) is stored only as a SHA-256 digest; the password only as a PHC string.

sql
CREATE TABLE users (
  id               bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email            text NOT NULL,
  email_verified   boolean NOT NULL DEFAULT false,
  password_hash    text NOT NULL,              -- $argon2id$v=19$m=19456,t=2,p=1$...
  totp_secret_enc  bytea,                       -- encrypted at rest (envelope key in KMS)
  totp_last_step   bigint NOT NULL DEFAULT 0,   -- replay protection (RFC 6238)
  password_changed timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX users_email_lower ON users (lower(email));

CREATE TABLE sessions (
  id_hash    bytea PRIMARY KEY,                -- sha256(session id); raw id only in the cookie
  user_id    bigint REFERENCES users(id) ON DELETE CASCADE,
  created_at timestamptz NOT NULL DEFAULT now(),   -- absolute timeout
  last_seen  timestamptz NOT NULL DEFAULT now()    -- idle timeout
);
CREATE INDEX sessions_user ON sessions (user_id);

CREATE TABLE refresh_tokens (
  token_hash bytea PRIMARY KEY,
  family_id  uuid NOT NULL,
  user_id    bigint NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  used       boolean NOT NULL DEFAULT false,
  expires_at timestamptz NOT NULL
);
CREATE TABLE revoked_families (family_id uuid PRIMARY KEY, revoked_at timestamptz NOT NULL DEFAULT now());

CREATE TABLE auth_tokens (                     -- password reset + email verification
  token_hash bytea PRIMARY KEY,
  user_id    bigint NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  purpose    text NOT NULL CHECK (purpose IN ('password_reset', 'email_verification')),
  expires_at timestamptz NOT NULL
);

-- refresh rotation: one transaction, the row lock makes concurrent refreshes queue.
-- Same checks, same order as refresh.Store.Rotate: unknown, revoked, expired -> 401;
-- used -> revoke the family, 401; otherwise mark used and insert the successor.
BEGIN;
SELECT t.user_id, t.family_id, t.used,
       (r.family_id IS NOT NULL) AS family_revoked,
       (t.expires_at <= now())   AS expired
  FROM refresh_tokens t
  LEFT JOIN revoked_families r ON r.family_id = t.family_id
 WHERE t.token_hash = $1
   FOR UPDATE OF t;
-- no row OR family_revoked OR expired -> ROLLBACK; answer 401 invalid_grant
-- used = true -> INSERT INTO revoked_families (family_id) VALUES ($family) ON CONFLICT DO NOTHING;
--                COMMIT; answer 401 (reuse detected)
UPDATE refresh_tokens SET used = true WHERE token_hash = $1 AND NOT used;   -- 1 row, or someone won the race
INSERT INTO refresh_tokens (token_hash, family_id, user_id, expires_at)
SELECT $2, $3, $4, now() + interval '30 days'
 WHERE NOT EXISTS (SELECT 1 FROM revoked_families WHERE family_id = $3);   -- 0 rows -> ROLLBACK, 401
COMMIT;

-- single-use reset token: consume and read in one statement
DELETE FROM auth_tokens
 WHERE token_hash = $1 AND purpose = 'password_reset'
RETURNING user_id, expires_at;

-- after a reset: end everything
DELETE FROM sessions WHERE user_id = $1;
INSERT INTO revoked_families SELECT DISTINCT family_id FROM refresh_tokens WHERE user_id = $1 ON CONFLICT DO NOTHING;

-- housekeeping job
DELETE FROM sessions WHERE last_seen < now() - interval '30 minutes' OR created_at < now() - interval '12 hours';
DELETE FROM auth_tokens WHERE expires_at < now();

Argon2id cost and concurrency Good to know ​

Each IDKey call allocates its m KiB for the duration of the hash (the benchmark shows 19.9 MB per operation at the OWASP parameters and 67.1 MB at RFC 9106's second option). Peak memory is therefore m × concurrent logins: 100 simultaneous logins at 19 MiB is about 2 GB. Bound concurrency with a semaphore around Verify (a buffered channel of size N), and put the throttling check before the hash so a flood of bad logins cannot buy unlimited memory. OWASP also warns that too high a work factor can be "used by an attacker to carry out a denial of service attack by exhausting the server's CPU with a large number of login attempts".

Solving the classic problems ​

BugSymptomFixCost
Fast or unsalted password hashBreach → passwords cracked in hoursArgon2id PHC + rehash on login15-30 ms CPU and 19-64 MiB per login
== on secrets, quick exit for unknown usersAccount enumeration by timingsubtle.ConstantTimeCompare, dummy hashOne extra hash per failed login
Different messages for unknown user / wrong passwordAccount enumeration by messageOne generic message, same statusSlightly worse UX
Session ID kept at loginSession fixationRotate / RenewTokenNone
Session ID guessable or stored rawHijacking; store leak = live sessions256-bit crypto/rand, store sha256(id)None
Cookie without flagsTheft via XSS or plain HTTP; CSRF__Host-, HttpOnly, Secure, SameSite=LaxNone
JWT alg trustedForged tokensWithValidMethods, key per algorithmNone
aud/iss uncheckedToken for service A accepted by BWithAudience, WithIssuerNone
Long-lived JWT, no revocationLogout and bans do not work10-min access + rotating refresh + jti denylistRefresh endpoint, a table
Role check onlyIDOR / BOLAOwnership check after load, 404One comparison per handler
Cookie auth without CSRF defenceCross-site actionsCrossOriginProtection + session-bound tokenToken plumbing in forms
template.HTML(userInput)Stored XSSbluemonday before the conversionSanitizer per rich field
Reset token stored raw, reusable, long-livedAccount takeover from a DB readHash, single use, 30 min, end sessionsA table and a job
Hard lockoutAttackers lock users outExponential delay, cappedSlower recovery for bots, not users
TOTP without replay checkPhished code reused within 90 sTrack last accepted stepOne column
Logout deletes cookie onlyCopied cookie still worksDestroy server-side + revoke refreshNone

Upgrading a legacy hash scheme without a mass reset ​

A table of sha1(salt+pw) or bcrypt hashes can move to Argon2id in two ways. Lazy: at each successful login, verify with the old scheme, then store password.Hash(plain, OWASP) (the After handler does this for parameter changes). Wrapped: hash every old hash immediately, argon2id(sha1hash), mark rows scheme = 'wrapped-sha1', and at login compute argon2id(sha1(salt+pw)); this protects dormant accounts too, at the cost of one more code path. OWASP notes the lazy approach leaves hashes "never ... upgraded if the user doesn't log back into the application" and suggests expiring those and requiring a reset.

Choosing what the 401 says ​

Return the same status, body and timing for unknown user, wrong password, locked account (after the delay is over) and unverified email, and tell the user the details by email ("someone tried to log in", "please verify your address"). The one exception is throttling: 429 with Retry-After is fine because it is keyed on the typed identifier whether or not the account exists, so it reveals nothing.

Mixing cookies and bearer tokens on one API ​

A web app and a mobile app often share an API. Accept both, in a fixed order (RequireUser(SessionAuth, Bearer(JWTVerifier(issuer))), tested in Middleware and authorization), apply the CSRF middleware only when the credential came from a cookie (bearer requests are not CSRF-able), record the method in Identity.Method, and require a fresh session (not a long-lived token) for sensitive actions such as changing the email or payout account.

Choosing ​

SituationUseExtra techniqueReason
Server-rendered Go appServer-side session (scs or the session pattern)CrossOriginProtection + CSRF token, html/templateInstant revocation, no token storage in JS
First-party SPA on the same siteSession cookie with SameSite=LaxCSRF token in a header, AddTrustedOrigin for the SPA originSame as above; avoid tokens in localStorage
Mobile appShort JWT access + rotating refresh tokenRefresh token in the OS keychainNo cookies; offline verification at the API
Service to serviceJWT (EdDSA/ES256) or mTLSaud per service, short TTL, client_credentialsVerifiable without a call to the issuer
Many APIs, one identity providerOIDC at the edge, JWT access tokens insideJWKS cache with refresh on unknown kidKey rotation without redeploys
Third-party loginx/oauth2 + go-oidcPKCE, state, nonce, then your own sessionIdentity from the ID token
New password storageArgon2id, OWASP m=19 MiB t=2 p=1 or RFC 9106 64 MiB t=3 p=4Rehash on login, semaphoreMemory-hard
Existing bcryptKeep, cost ≥ 12Migrate to Argon2id on loginNo forced reset
FIPS environmentPBKDF2-HMAC-SHA-256, 600,000+ iterationscrypto/pbkdf2 (Go 1.24)Approved algorithm
Staff / admin accountsPassword + TOTP or passkeysStep-up for sensitive actionsPhished password is not enough
Consumer accountsPasskeys offered, password ≥ 15 chars + breached checkEmail verification, rate limitsNIST SP 800-63B-4
Rich-text user contentbluemonday.UGCPolicy then template.HTMLCSP as an extra layerAllow-list sanitizer

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

The simplest correct design is the one in this module: Argon2id hashes in users, a sessions table (or scs with postgresstore), a __Host- session cookie, session.Load and the CSRF middleware on every route, RequireUser on the authenticated group, and ownership checks in handlers. No JWT at all. Example: a Go invoicing app for a few hundred customers, one PostgreSQL, one binary; logout, password reset and "disable user" all take effect on the next request because they delete rows.

Modular monolith and multiple databases ​

Authentication becomes a module (internal/auth) that owns users, sessions, auth_tokens and the password hasher, and exposes only Authenticate(r) (*Identity, error), RequireUser and From(ctx). Other modules never read the users table; they receive an Identity from the context and enforce their own object rules (billing checks invoice ownership, catalogue checks shop membership). If sessions move to Redis for speed while users stay in PostgreSQL, a password reset must delete from both; do it in the auth module, with the Redis delete after the PostgreSQL commit and a retry, because the two stores are not atomic.

Microservices ​

A dedicated auth service issues tokens; the other services only verify. The browser still talks to a backend-for-frontend (BFF) with a session cookie; the BFF holds the user's access and refresh tokens server-side and calls internal services with Authorization: Bearer <access token>. Each service verifies with WithValidMethods([]string{"EdDSA"}), WithIssuer("https://auth.internal"), WithAudience("<its own name>"), and keys from the auth service's JWKS. Example flow: browser → BFF (__Host-sid) → orders (aud: orders, 10 min) → payments, where orders exchanges or requests a token with aud: payments instead of forwarding its own (a forwarded token with a broad audience lets any compromised service act as the user everywhere). What does not survive across services: the server-side session (only the BFF has it), instant revocation (each service accepts a valid token until exp unless it checks a shared denylist), and object-level authorization (every service must do its own). The microservices project builds an auth service in this shape.

Distributed data: replicas, caches, multi-region ​

Sessions in a Redis cluster or a replicated table bring replica lag into authentication: a logout written to the primary may not have reached the replica that serves the next read, so the "deleted" session works for a few hundred milliseconds. Read session state from the primary (or from Redis without replica reads) for anything that must be immediate, such as logout and password change. JWT verification is naturally multi-region (only public keys are needed), but JWKS caches and denylists must be replicated, and clocks must be within the leeway (30 s here) because exp, nbf and iat compare wall-clock times on different hosts. Rate-limit and lockout counters per region allow an attacker N attempts per region; for credential stuffing that matters less than for a targeted account, so keep per-account counters global (a central Redis) and per-IP ones local.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesAuthentication practice
1× (one instance)Everything fits in one processIn-memory or PostgreSQL sessions, Argon2id OWASP params, lockout in memory
10× (several instances behind a load balancer)Sessions and counters must be sharedRedis or PostgreSQL session store, central lockout counters, hash-concurrency semaphore per instance, trusted real-IP for per-IP limits
100× (many services, many regions)Per-request lookups and the login hash dominateJWT access tokens verified locally with a JWKS cache, refresh at the auth service, passkeys to cut password hashing and phishing, dedicated login service with its own capacity and rate limits

Lab ​

1. Run the tests (real) ​

cd docs/snippets/go/authentication-in-go/go
gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok  academy/authentication-in-go/after     1.612s
# ok  academy/authentication-in-go/authmw    1.440s
# ok  academy/authentication-in-go/before    1.439s
# ok  academy/authentication-in-go/csrf      1.438s
# ok  academy/authentication-in-go/jwks      1.620s
# ok  academy/authentication-in-go/jwtauth   1.530s
# ok  academy/authentication-in-go/lockout   1.407s
# ok  academy/authentication-in-go/mfa       1.412s
# ok  academy/authentication-in-go/password  3.971s
# ok  academy/authentication-in-go/refresh   1.499s
# ok  academy/authentication-in-go/reset     1.412s
# ok  academy/authentication-in-go/sanitize  1.404s
# ok  academy/authentication-in-go/scsdemo   1.491s
# ok  academy/authentication-in-go/session   1.486s

2. Measure the password hashes (real) ​

go test -run '^$' -bench . -benchmem ./password
# cpu: Apple M4 Pro
# BenchmarkArgon2idOWASP-12             76   15467632 ns/op   19927483 B/op   33 allocs/op
# BenchmarkBcryptCost12-12               6  175956194 ns/op       5534 B/op   10 allocs/op
# BenchmarkArgon2idRFC9106Second-12     42   26944114 ns/op   67120044 B/op   91 allocs/op

Read it as: one OWASP-parameter Argon2id costs about 15 ms and 19 MiB, so 100 concurrent logins need about 2 GB; bcrypt at cost 12 costs 176 ms of one core but almost no memory, which is exactly why GPUs handle it better than Argon2id.

3. Watch alg confusion fail (real) ​

go test -run 'TestAlgConfusionRejected|TestKeyRotation' -v ./jwtauth
# --- PASS: TestAlgConfusionRejected   HS256-with-public-key and "none" both rejected
# --- PASS: TestKeyRotation            old and new kid accepted during overlap; retired kid rejected

The error the HS256 forgery gets, printed from a scratch program against the same package: token signature is invalid: signing method HS256 is invalid.

4. Prove refresh reuse detection and single-use resets (real) ​

go test -run 'Reuse|Concurrent|SingleUse' -v ./refresh ./reset
# --- PASS: TestReuseRevokesFamily
# --- PASS: TestConcurrentRotateHasOneWinner     20 goroutines, 1 winner
# --- PASS: TestSingleUseHashedAndSessionsEnded
# --- PASS: TestConcurrentConfirmHasOneWinner    10 goroutines, 1 winner

5. Session fixation and enumeration, before vs after (real) ​

go test -run 'TestBeforeWeaknesses' -v ./before
# --- PASS: TestBeforeWeaknesses   planted "attacker-chosen" id logged in as bob; session survives logout
go test -run 'TestUnknownUserAndWrongPasswordLookTheSame|TestLoginRotatesAndSetsFlags' -v ./after
# --- PASS: TestUnknownUserAndWrongPasswordLookTheSame   same 401 body, 2 hash computations
# --- PASS: TestLoginRotatesAndSetsFlags                 planted id rejected after login

6. The CSRF-protected browser flow (test real; curl against a server expected) ​

after.Server.Secure(p) is the CSRF-wired stack: the same endpoints plus GET /csrf-token, which starts an anonymous session when there is none and returns the token for the current session, all behind csrf.Protector.Middleware (with SessionID: after.SessionIDFromCookie). The browser flow itself is a real test:

go
package after

import (
	"encoding/json"
	"net/http"

	"academy/authentication-in-go/csrf"
	"academy/authentication-in-go/session"
)

// SessionIDFromCookie is what csrf.Protector binds its tokens to.
func SessionIDFromCookie(r *http.Request) string {
	if c, err := r.Cookie(session.CookieName); err == nil {
		return c.Value
	}
	return ""
}

// CSRFToken serves GET /csrf-token: it starts an anonymous session when the
// browser has none (so the login form has something to bind a token to)
// and returns the token for the current session. Call it again after login:
// rotation gives a new session ID, so the old token no longer matches.
func (s *Server) CSRFToken(p *csrf.Protector) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		id := SessionIDFromCookie(r)
		if _, err := s.Sessions.Get(id); id == "" || err != nil {
			id = s.Sessions.Create(0)
			http.SetCookie(w, session.Cookie(id))
		}
		w.Header().Set("Cache-Control", "no-store")
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"csrf_token": p.Token(id)})
	}
}

// Secure is the production shape of Routes: the same endpoints plus
// GET /csrf-token, with csrf.Protector in front of every unsafe method.
// Put csrf.WithCrossOriginProtection (Go 1.25) outside it.
func (s *Server) Secure(p *csrf.Protector) http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /csrf-token", s.CSRFToken(p))
	mux.HandleFunc("POST /login", s.Login)
	mux.HandleFunc("POST /logout", s.Logout)
	mux.HandleFunc("GET /me", s.Me)
	return s.Sessions.Load(p.Middleware(mux))
}
go
package after

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"academy/authentication-in-go/csrf"
	"academy/authentication-in-go/session"
)

// The lab flow end to end: fetch a token (anonymous session), log in with
// it, fetch a new token for the rotated session, log out with it; a logout
// without a token is refused.
func TestSecureStackBrowserFlow(t *testing.T) {
	s, _ := newServer(t)
	p := &csrf.Protector{Secret: []byte("0123456789abcdef0123456789abcdef"), SessionID: SessionIDFromCookie}
	h := s.Secure(p)

	getToken := func(c *http.Cookie) (string, *http.Cookie) {
		req := httptest.NewRequest("GET", "https://app.example.test/csrf-token", nil)
		if c != nil {
			req.AddCookie(c)
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		var body map[string]string
		json.NewDecoder(rec.Body).Decode(&body)
		if cs := rec.Result().Cookies(); len(cs) > 0 {
			c = &http.Cookie{Name: cs[0].Name, Value: cs[0].Value}
		}
		return body["csrf_token"], c
	}
	send := func(path string, form url.Values, c *http.Cookie) *httptest.ResponseRecorder {
		req := httptest.NewRequest("POST", "https://app.example.test"+path, strings.NewReader(form.Encode()))
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		req.Header.Set("Origin", "https://app.example.test")
		req.RemoteAddr = "192.0.2.10:5000"
		if c != nil {
			req.AddCookie(c)
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		return rec
	}

	tok, anon := getToken(nil)
	if tok == "" || anon == nil || anon.Name != session.CookieName {
		t.Fatalf("no anonymous session/token: %q %v", tok, anon)
	}
	if rec := send("/login", url.Values{"email": {"alice@example.test"}, "password": {"correct horse battery staple"}}, anon); rec.Code != 403 {
		t.Fatalf("login without token: %d", rec.Code)
	}
	rec := send("/login", url.Values{"email": {"alice@example.test"}, "password": {"correct horse battery staple"}, "csrf_token": {tok}}, anon)
	if rec.Code != http.StatusNoContent {
		t.Fatalf("login with token: %d %s", rec.Code, rec.Body)
	}
	authed := &http.Cookie{Name: session.CookieName, Value: rec.Result().Cookies()[0].Value}
	if rec := send("/logout", url.Values{"csrf_token": {tok}}, authed); rec.Code != 403 {
		t.Fatalf("pre-login token accepted after rotation: %d", rec.Code)
	}
	tok2, _ := getToken(authed)
	if rec := send("/logout", nil, authed); rec.Code != 403 {
		t.Fatalf("logout without token: %d", rec.Code)
	}
	if rec := send("/logout", url.Values{"csrf_token": {tok2}}, authed); rec.Code != http.StatusNoContent {
		t.Fatalf("logout with token: %d", rec.Code)
	}
}
go test -run TestSecureStackBrowserFlow -v ./after      (real)
# --- PASS: TestSecureStackBrowserFlow   GET /csrf-token -> anonymous __Host-sid + token;
#     POST /login without token 403, with token 204 (rotated cookie);
#     old token after rotation 403; fresh token -> POST /logout 204; no token 403

Against a running server (expected, not run): wrap s.Secure(p) with csrf.WithCrossOriginProtection in a main serving https://localhost:8443 (self-signed certificate), then:

curl -k -c jar -b jar https://localhost:8443/csrf-token
# {"csrf_token":"<nonce>.<mac>"}  and Set-Cookie: __Host-sid=<anonymous id>      (expected)
curl -k -c jar -b jar -X POST https://localhost:8443/login -H 'Origin: https://localhost:8443' \
     --data-urlencode 'email=alice@example.test' --data-urlencode 'password=correct horse battery staple' \
     --data-urlencode 'csrf_token=<nonce>.<mac>'
# HTTP/2 204, Set-Cookie: __Host-sid=<new id>                                       (expected)
curl -k -c jar -b jar https://localhost:8443/csrf-token
# {"csrf_token":"<token for the new session>"}                                      (expected)

Then the three rejections:

curl -k -i -X POST https://localhost:8443/logout -H 'Sec-Fetch-Site: cross-site' -b '__Host-sid=<id>'
# HTTP/2 403   cross-origin request detected from Sec-Fetch-Site header        (expected)
curl -k -i -X POST https://localhost:8443/logout -H 'Origin: https://evil.example.test' -b '__Host-sid=<id>'
# HTTP/2 403   cross-origin request detected, and/or browser is out of date: ...  (expected)
curl -k -i -X POST https://localhost:8443/logout -b '__Host-sid=<id>'
# HTTP/2 403   forbidden: CSRF check failed   (no token; the session-bound token layer)  (expected)

For PHP/Laravel developers ​

Laravel gives you this whole chapter as configuration; Go gives you the parts. Laravel's Auth::attempt($credentials) verifies with the Hash facade (bcrypt by default; argon and argon2id drivers available, Hash::needsRehash for upgrades), and the docs' login example follows it with $request->session()->regenerate(), which is session.Rotate here. The web middleware group adds the session and CSRF protection: in Laravel 13 the PreventRequestForgery middleware uses "a two-layer approach", first the Sec-Fetch-Site header ("If the header indicates the request came from the same origin, the request is allowed immediately without any token verification"), then the classic session token (@csrf, the _token field), the same layering as CrossOriginProtection in front of csrf.Protector here; the starter kits add "rate limiting ... to login attempts" (one minute after several failures), and the Password broker implements reset with 'expire' => 60 and 'throttle' => 60.

Laravel Breeze/Sanctum comparison. Breeze was, in the Laravel 11 docs' words, "a minimal, simple implementation of all of Laravel's authentication features, including login, registration, password reset, email verification, and password confirmation". The Laravel 12 release notes then said: "With the introduction of our new application starter kits, Laravel Breeze and Laravel Jetstream will no longer receive additional updates." In Laravel 13 the React, Vue and Livewire starter kits "use Laravel Fortify to handle authentication", with two-factor authentication as a Fortify feature; that is the closest thing to the after, reset, lockout and mfa packages combined. Sanctum covers the token side in two modes: API tokens "inspired by GitHub and other applications which issue 'personal access tokens'", stored in a database table and "hashed using SHA-256 hashing before being stored", which are opaque tokens like this chapter's refresh tokens (revocable by deleting a row), not JWTs; and SPA authentication where "Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel's built-in cookie based session authentication services", which is the "first-party SPA" row of Choosing.

php
// Laravel 13: login with rotation, generic error, throttling handled by the starter kit
if (Auth::attempt($request->only('email', 'password'))) {
    $request->session()->regenerate();            // = session.Rotate
    return redirect()->intended('/dashboard');
}
return back()->withErrors(['email' => 'The provided credentials do not match our records.']);
// Sanctum API token: opaque, SHA-256 hashed before storage; abilities as the second argument
$token = $user->createToken('mobile', ['orders:read'])->plainTextToken;
Laravel 13Go (this chapter)
Hash::make, Hash::check, Hash::needsRehashpassword.Hash, password.Verify (returns needsRehash)
config/hashing.php bcrypt.rounds, argon.memory/time/threadspassword.Params, password.BcryptCost
Auth::attempt + session()->regenerate()after.Login + session.Store.Rotate
session()->invalidate(), regenerateToken() on logoutStore.Destroy + ClearCookie
PreventRequestForgery (Sec-Fetch-Site, then @csrf token; originOnly, allowSameSite)http.CrossOriginProtection, then csrf.Protector
RateLimiter / login throttlinglockout.Guard
Password::sendResetLink, Password::resetreset.Service
MustVerifyEmail, signed verification URLsreset.SendVerification, ConfirmEmail
Fortify two-factor authenticationmfa (pquerna/otp)
Sanctum API tokensOpaque hashed tokens (refresh pattern) or JWT (jwtauth)
Sanctum SPA authenticationSession cookie + CSRF for a first-party SPA
Breeze (Laravel 11 and earlier) / starter kits on Fortify (12, 13)after + reset + lockout + mfa, wired by you
Blade's escaped echo (double braces)html/template contextual autoescaping

Common misconceptions ​

BeliefReality
SHA-256 with a salt is a fine password hashToo fast; use Argon2id (or bcrypt for legacy)
A salt must be secretIt is stored with the hash; the pepper is the secret part
More Argon2 threads means harder to crackp divides the memory into lanes; memory and passes set the cost
bcrypt hashes the whole password72 bytes maximum; x/crypto rejects longer input
Comparing hashes with == is harmlessCopy-pasted to tokens and MACs it leaks; the quick-exit path leaks accounts
Complexity rules make passwords strongNIST SP 800-63B-4 forbids them; length and blocklists work
Keeping the anonymous session ID at login is fineSession fixation; rotate on every privilege change
A signed cookie session can be revokedNothing to delete on the server; it is valid until it expires
A JWT is encryptedJWS payloads are base64url, readable by anyone
A valid JWT signature means a valid tokeniss, aud, exp, typ and the algorithm must all be checked
Logout revokes a JWTOnly expiry, a denylist or key retirement do
Auth middleware is authorizationObject ownership is checked in the handler (IDOR/BOLA)
SameSite=Lax is complete CSRF protectionSame-site attackers, GET side effects and old browsers remain
Sanitizing input prevents XSSOutput encoding at render time does; sanitize only HTML you render as HTML
Reset links can log the user inOWASP: do not auto-login; end existing sessions instead
Lock accounts after five failuresThat is a DoS button; use capped exponential delays
totp.Validate prevents replayIt is stateless; store the last accepted step

Cheat sheet ​

TopicRemember
Hashargon2.IDKey, PHC string, m=19456 t=2 p=1 (OWASP) or 64 MiB t=3 p=4 (RFC 9106), 16-byte salt
bcryptCost ≥ 10 (12 here), 72-byte limit, bcrypt.Cost for rehash
PepperHMAC with a key from a vault; base64(HMAC-SHA-384) before bcrypt
Comparesubtle.ConstantTimeCompare / hmac.Equal; dummy hash for unknown users
ErrorsOne message: "invalid email or password"; 429 + Retry-After for throttling
Policy≥ 15 chars (8 with MFA), allow ≥ 64, blocklist, no composition, no forced rotation
Session ID32 bytes crypto/rand, base64url, store sha256(id)
Cookie__Host-sid; Path=/; HttpOnly; Secure; SameSite=Lax
RotationNew ID on login, logout, password change, role change
TimeoutsIdle 15-30 min (2-5 high-value), absolute 4-12 h, enforced server-side
JWTWithValidMethods, WithIssuer, WithAudience, WithExpirationRequired, WithLeeway(30s)
KeysEdDSA or ES256; kid for rotation; retire after max TTL; JWKS cache with rate-limited refresh
TokensAccess 5-15 min; refresh opaque, hashed, rotated, reuse revokes the family
IdentityUnexported ctx key; From(ctx); handler checks ownership, 404 for others' objects
CSRFCrossOriginProtection (1.25) + session-bound HMAC token; logout is POST
XSSValidate at input, bluemonday for rich HTML, html/template always
Reset256-bit token, hash stored, 30-60 min, single use, generic answer, end sessions
TOTPpquerna/otp, 30 s, skew 1, reject replays, hashed recovery codes

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why is sha256(salt + password) not an acceptable password hash, and what do you use in Go instead? Must-know ​

Answer

Answer: The salt defeats precomputed tables but not guessing: SHA-256 is designed to be fast, so an attacker with the table tries billions of candidates per second per GPU. Use a deliberately slow, memory-hard function: argon2.IDKey from golang.org/x/crypto/argon2 with at least OWASP's m=19456 KiB, t=2, p=1 and a 16-byte random salt, stored as a PHC string; bcrypt (cost ≥ 10, 72-byte limit) only for legacy systems.

2 — What does the PHC string $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash> let you do that a bare hash column does not? Good to know ​

Answer

Answer: It carries the algorithm, version, parameters and salt with the hash, so Verify recomputes with the parameters that were used for that row, old and new parameters coexist, and after a successful login you can compare the stored parameters with the current policy and rehash (needsRehash) while you still have the plaintext.

3 — Your login answers "no such user" in 1 ms and "wrong password" in 15 ms with the same message. What is wrong and how do you fix it? Must-know ​

Answer

Answer: The timing still enumerates accounts (the quick-exit problem OWASP describes). Compute a dummy Argon2id hash with the current parameters when the user is missing, verify against it, and fail with the same status and body; compare all secrets with subtle.ConstantTimeCompare; and throttle per typed identifier whether or not the account exists.

4 — What does NIST SP 800-63B-4 require of a password policy, and what does it forbid? Important ​

Answer

Answer: Minimum 15 characters for single-factor passwords (8 if only used with MFA), permit at least 64, compare against a blocklist of common and compromised passwords, salt (≥ 32 bits) and hash with a password hashing scheme, and rate-limit failures (≤ 100 consecutive). It forbids composition rules, forced periodic changes (except on evidence of compromise) and knowledge-based prompts.

5 — Why must the session ID change at login, and how do you do it with scs and with the hand-written store? Must-know ​

Answer

Answer: Otherwise an attacker who planted a known session ID in the victim's browser (session fixation) is logged in as the victim when the victim logs in. With alexedwards/scs call sm.RenewToken(r.Context()) before Put; with the session package call Store.Rotate(oldID, userID), which deletes the old record and issues a fresh 256-bit ID. Do the same on logout, password change and role change.

6 — Which cookie attributes does a session cookie need, and what does the __Host- prefix add? Important ​

Answer

Answer: HttpOnly (no script access), Secure (HTTPS only), SameSite=Lax or Strict (not sent on cross-site POSTs and subresources), Path=/, no Domain. The __Host- prefix makes the browser refuse the cookie unless it is Secure, has Path=/ and has no Domain, so a sibling subdomain cannot overwrite it.

7 — Explain the RS256-to-HS256 alg confusion attack and the golang-jwt v5 option that prevents it. Must-know ​

Answer

Answer: The attacker changes alg to HS256 and signs with HMAC using the verifier's public key bytes as the secret; a library that trusts alg and hands the "key" to HMAC accepts it. jwt.WithValidMethods([]string{"EdDSA"}) (or your one asymmetric algorithm) rejects any other alg (token signature is invalid: signing method HS256 is invalid), and RFC 8725 adds that each key must be used with exactly one algorithm.

8 — golang-jwt v5 accepted a token minted for another service. Which checks were missing? Important ​

Answer

Answer: v5 validates exp and nbf when present but checks iss and aud only when asked. Add WithIssuer(...), WithAudience("<this service>"), WithExpirationRequired(), a small WithLeeway, and an explicit typ check so ID tokens or refresh tokens cannot be used as access tokens.

9 — How does refresh token rotation detect theft, and what happens to the legitimate user? Important ​

Answer

Answer: Each refresh returns a new refresh token and marks the old one used, keeping the family relation. If a used token is presented again, either the attacker or the user is replaying it; the server cannot tell which, so it revokes the whole family (RFC 9700 section 4.14.2). The legitimate user's current token stops working and they log in again, which ends the attacker's access too.

10 — An authenticated user can read /invoices/1002 that belongs to someone else. Where is the bug, and what should the response be? Must-know ​

Answer

Answer: Missing object-level authorization in the handler (IDOR, OWASP API1:2023). After loading the invoice, compare its owner (or tenant) with the identity from the context; answer 404 for objects the caller may not see so ids cannot be probed, and add AND owner_id = $2 in the query as defence in depth.

11 — With SameSite=Lax session cookies, why do you still need CSRF protection, and what does Go 1.25 add? Important ​

Answer

Answer: An explicit SameSite=Lax does not stop same-site attackers (a compromised sibling subdomain) or state-changing GETs, and browsers that ignore the attribute send the cookie anyway. If the attribute is missing, browsers that apply Lax by default use a more permissive version that still sends the cookie on cross-site POSTs within two minutes of it being set (MDN), and others send it always; so always set SameSite explicitly. Go 1.25's http.CrossOriginProtection rejects non-safe requests whose Sec-Fetch-Site is not same-origin or none, or whose Origin does not match Host; keep a session-bound token for browsers that send neither header.

12 — List the properties of a safe password reset flow. Must-know ​

Answer

Answer: The same response (and similar timing) for existing and unknown emails; a random token of at least 128 bits; only its hash stored; a short expiry (30-60 minutes); single use, consumed atomically; older tokens invalidated; a link built from configuration, not the Host header; Referrer-Policy: no-referrer; and after the reset, every session and refresh token of the user revoked, with no automatic login.

13 — Why does totp.Validate alone not satisfy RFC 6238, and how do you fix it? Good to know ​

Answer

Answer: It is stateless: within its window (30 s step, skew 1) the same code validates again, while RFC 6238 says the verifier "MUST NOT accept the second attempt of the OTP after the successful validation". Find which time step matched (GenerateCodeCustom for each step in the window), and accept only if it is greater than the last accepted step stored for the user.

14 — What does a secure logout do for a cookie session and for a token-based mobile client? Good to know ​

Answer

Answer: Cookie session: a CSRF-protected POST that deletes the server-side session, sends an expired cookie (Max-Age=0) and optionally Clear-Site-Data. Mobile client: revoke the refresh token family on the server and delete tokens from the keychain; the access token lives until exp unless its jti is denylisted. Both: offer "log out everywhere".

Glossary ​

TermMeaning
AuthenticationProving who the caller is
AuthorizationDeciding what that caller may do to which object
Password hashingStoring a slow, salted one-way function of the password
Argon2idMemory-hard password hash (RFC 9106), argon2.IDKey in Go
RFC 9106 parameterst, m, p recommendations; second option t=3, p=4, 64 MiB
bcryptAdaptive Blowfish-based password hash; cost 4-31, 72-byte limit
Cost / work factorParameter that makes each hash slower (bcrypt 2^cost rounds)
PHC string format$id$v=..$params$salt$hash encoding of a password hash
SaltPer-password random value stored with the hash
PepperSecret key applied to all passwords, stored outside the database
Rehash on loginUpgrading a stored hash after a successful verify
Constant-time compareComparison whose time does not depend on where inputs differ (crypto/subtle)
Timing attackLearning secrets or facts from response times
Dummy hashHash computed for unknown users so failures cost the same
User enumerationLearning which accounts exist from responses or timing
Password policy (NIST 800-63B)Length, blocklist, no composition rules, no forced rotation
BlocklistList of common or breached passwords to reject
SessionServer-side record of a logged-in user
Server-side storeWhere sessions live: memory, Redis, SQL
Session ID entropyUnpredictability of the ID; ≥ 64 bits, 256 here from crypto/rand
Session fixationAttacker plants a known session ID before the victim logs in
Rotation on loginIssuing a new session ID at a privilege change
Idle timeoutSession ends after inactivity
Absolute timeoutSession ends a fixed time after login
HttpOnlyCookie flag hiding the cookie from JavaScript
SecureCookie flag restricting it to HTTPS
SameSiteCookie attribute limiting cross-site sending (Strict, Lax, None)
__Host- prefixCookie name prefix requiring Secure, Path=/, no Domain
alexedwards/scsGo server-side session manager with pluggable stores
gorilla/sessionsGo cookie and filesystem session package (signed/encrypted cookies)
JWTSigned JSON claims (RFC 7519), compact JWS form
golang-jwt/jwt v5The maintained Go JWT library, github.com/golang-jwt/jwt/v5
HS256HMAC-SHA-256 JWT signature with a shared secret
RS256 / ES256 / EdDSARSA, ECDSA P-256 and Ed25519 JWT signatures
Claims validationChecking exp, nbf, iat, aud, iss (and sub, typ)
Alg confusionAttacker-chosen alg (none, HS256 with a public key)
kidJWT header naming the key to verify with
Key rotationIntroducing a new signing key and retiring the old after max TTL
JWKSJSON Web Key Set: public keys published at a URL (RFC 7517)
Access tokenShort-lived credential presented to APIs
Refresh tokenLong-lived, revocable credential traded for new access tokens
Refresh token rotationNew refresh token per use; reuse revokes the family
RevocationInvalidating a credential before it expires
jti denylistList of revoked token IDs kept until their exp
OAuth2Delegated authorization protocol; golang.org/x/oauth2
OIDCIdentity layer on OAuth2; coreos/go-oidc verifies ID tokens
PKCEProof key for code exchange, protects the authorization code
Auth middlewareWrapper that authenticates and puts identity in the context
Context identityThe Identity value under an unexported context key
IDOR / BOLAMissing object-level authorization (OWASP API1:2023)
CSRFCross-site request forgery: another site acting with the user's cookies
Double-submit cookieCSRF token in a cookie and in the request; signed, session-bound variant recommended
Synchronizer tokenPer-session CSRF token checked on every unsafe request
Origin checkComparing the Origin header with the expected origin
Sec-Fetch-SiteFetch metadata header: same-origin, same-site, cross-site, none
http.CrossOriginProtectionGo 1.25 net/http CSRF middleware based on fetch metadata
ValidationRejecting input that does not match an allow-list
SanitizationRemoving disallowed HTML from content rendered as HTML (bluemonday)
Output encodingEscaping data for its render context (html/template)
#ZgotmplZhtml/template placeholder for an unsafe URL or CSS value
Password reset tokenRandom, hashed, single-use, expiring link secret
Email verificationProving control of an address with a single-use token
Account lockoutDelaying or blocking attempts on one account after failures
Rate limitingBounding attempts per source (token bucket, x/time/rate)
Credential stuffingTrying leaked username/password pairs across many accounts
MFAMulti-factor authentication
TOTPTime-based one-time password (RFC 6238), pquerna/otp
Recovery codesSingle-use backup codes for a lost second factor
Passkey / WebAuthnOrigin-bound public-key credential; go-webauthn
Secure logoutDeleting server-side session state, expiring the cookie, revoking refresh tokens
Laravel BreezeLaravel's minimal auth scaffolding up to Laravel 11, replaced by starter kits
Laravel FortifyBackend auth implementation used by the Laravel 13 starter kits
Laravel SanctumLaravel package for opaque API tokens and SPA cookie authentication

References ​

Built by Morteza Negahi