Skip to content

Auth Overview ​

Added: v1.6.0

Zen's auth system is built around the Authenticator interface - any authentication strategy can be plugged in by implementing a single method.

Interface ​

go
type Authenticator interface {
    Authenticate(r *http.Request) (*User, error)
}

Return a *User on success or an error to trigger the configured error handler.

Usage ​

Apply authentication as middleware. Optionally skip routes with SkipPaths:

go
r.EnableAuth(jwtAuth)
r.EnableAuth(jwtAuth, zen.SkipPaths("/health"))

User Struct ​

go
type User struct {
    ID       string
    Username string
    Roles    []string
    Claims   map[string]any
}
  • Role-Based Access (RBAC) - r.EnableRBAC, RequireRole, and user.HasRole("admin")
  • Permission-Based Access (PBAC) - RequirePermission, RequireAnyPermission, RequireAllPermissions, and user.HasPermission(...)
  • Claim-Based Access - RequireClaim for enforcing specific claim values
  • Roles list role names assigned to the user; permissions are resolved through the role registry
  • Claims carry provider-specific data (e.g., OIDC claims).

Retrieving the User ​

go
user := c.GetUser()

Returns the authenticated *User from the context, or nil if not authenticated.

Password Helpers ​

Use the built-in password helpers for hashing and validation:

go
hashed, err := auth.HashPassword("secret")
hashed, err := auth.HashPassword("secret", 12) // optional bcrypt cost

ok := auth.ValidatePassword(hashed, "secret")

Released under the MIT License.