Skip to content

Session Auth ​

Added: v1.1.0

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 ​

go
import "github.com/Pavan-Silva/go-zen/auth"

store := auth.NewInMemorySessionStore(24 * time.Hour)
sessionAuth := &auth.SessionAuth{
    CookieName: "session",
    Store:      store,
}

r.EnableAuth(sessionAuth)

Login ​

go
sessionID := "generated-unique-id"
store.Set(sessionID, &zen.User{ID: "user-id-123"})
http.SetCookie(c.Response, &http.Cookie{
    Name:     "session",
    Value:    sessionID,
    Path:     "/",
    HttpOnly: true,
    Secure:   true,
})

Logout ​

go
http.SetCookie(c.Response, &http.Cookie{
    Name:   "session",
    Value:  "",
    Path:   "/",
    MaxAge: -1,
})

Configuration ​

OptionDefaultDescription
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 ​

  1. The login handler creates a session ID, stores the user in the SessionStore, and sets a cookie
  2. Middleware reads the cookie, looks up the session ID in the Store
  3. On success, populates User with the value from the store
  4. On failure (missing, expired), returns 401 Unauthorized

Released under the MIT License.