Documentation
¶
Overview ¶
Typed sessions with the v14 secure defaults.
sessions.Handler[T] loads (or creates) one session per request and commits it automatically afterwards, 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.
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