Session Auth
Session-based authentication using an in-memory or custom SessionStore. Cookies carry the session ID; user data is looked up from the store on each request.
Usage
import "github.com/Pavan-Silva/go-zen/auth"
store := auth.NewInMemorySessionStore(24 * time.Hour)
sessionAuth := &auth.SessionAuth{
CookieName: "session",
Store: store,
}
r.Use(auth.RequireAuth(sessionAuth))
Login
sessionID := "generated-unique-id"
store.Set(sessionID, &auth.User{ID: "user-id-123"})
http.SetCookie(c.Response, &http.Cookie{
Name: "session",
Value: sessionID,
Path: "/",
HttpOnly: true,
Secure: true,
})
Logout
http.SetCookie(c.Response, &http.Cookie{
Name: "session",
Value: "",
Path: "/",
MaxAge: -1,
})
Configuration
| Option | Default | Description |
|---|---|---|
CookieName | "zen-session" | Cookie name |
Store | - | SessionStore implementation (required) |
Session authentication uses a SessionStore interface to look up session data. The built-in InMemorySessionStore is suitable for development. In production, implement SessionStore with Redis, PostgreSQL, or your preferred backend.
How It Works
- The login handler creates a session ID, stores the user in the
SessionStore, and sets a cookie - Middleware reads the cookie, looks up the session ID in the
Store - On success, populates
Userwith the value from the store - On failure (missing, expired), returns
401 Unauthorized