Documentation
¶
Overview ¶
Typed sessions with the v14 secure defaults.
sessions.Handler[T] loads (or creates) one session per request and commits it afterwards when the request changed it, unless a handler already committed or the response is a 4xx/5xx. Handlers read and write it through sessions.Get[T](ctx), so the payload stays a plain Go struct instead of a bag of any values.
A request that only reads the session, /profile here, sends no cookie and writes nothing, so nothing moves the expiry: the session ends MaxAge (8 hours below) after its last change, not after its last request. Call session.Commit(ctx) in such a handler to keep the visitor signed in. A page without the session cookie can also be stored by a shared cache, so send Cache-Control: private on one that depends on the session.
sessions.NewOptions sets Path "/", MaxAge 24h, SameSite=Lax and Secure=true; session cookies are always HttpOnly. Secure means the browser will NOT send the cookie over plain HTTP, including http://localhost, so this example sets opts.Secure = false to stay usable with curl, exactly as MIGRATION.md describes. Remove that line before deploying.
Learn: keep one typed struct per visitor in an encrypted cookie, guard routes on it, and rotate the session id after sign-in. Before: ../jwt-middleware
Run:
go run main.go
Try (curl's -c/-b flags keep the cookie jar between the calls):
curl -i -c jar.txt -b jar.txt -X POST -H "Content-Type: application/json" \
http://localhost:8080/signin -d '{"username":"maria","password":"maria_password"}' # 200, Set-Cookie: app_session
curl -i -c jar.txt -b jar.txt http://localhost:8080/profile # 200, the UserSession data
curl -s -c jar.txt -b jar.txt http://localhost:8080/count # 200, views 1, then 2, then 3...
curl -i -c jar.txt -b jar.txt -X POST http://localhost:8080/signout # 200, the cookie expires
curl -i -c jar.txt -b jar.txt http://localhost:8080/profile # 401, signed out
Next: ../auth-sdk