Documentation
¶
Overview ¶
Package forwardauth provides ForwardAuth middleware for reverse proxy authentication. It supports multiple authentication methods and integrates with session management for use with Traefik, Nginx, and other reverse proxies supporting ForwardAuth.
Index ¶
- Constants
- Variables
- func FiberCheckRoute(handler *Handler, store *fibersession.Store) fiber.Handler
- func FiberMiddleware(handler *Handler, store *fibersession.Store) fiber.Handler
- func GetPreferredFormat(c Context) string
- func IsHTMLRequest(c Context) bool
- func IsJSONRequest(c Context) bool
- func IsXMLRequest(c Context) bool
- func MergeScopesUnique(a, b []string) []string
- func NormalizeHost(host string) string
- func ParseScopesFromHeader(header string) []string
- func ScopesContain(scopes []string, target string) bool
- func SendErrorResponse(c Context, statusCode int, message string) error
- type AuthChecker
- type AuthHeaderBuilder
- type AuthMethod
- type AuthResult
- type Config
- type Context
- type ErrorCode
- type ErrorHandler
- type ErrorResponse
- type FiberContext
- func (c *FiberContext) Context() context.Context
- func (c *FiberContext) Get(key string) string
- func (c *FiberContext) Hostname() string
- func (c *FiberContext) JSON(v interface{}) error
- func (c *FiberContext) Locals(key string, value ...interface{}) interface{}
- func (c *FiberContext) Method() string
- func (c *FiberContext) Path() string
- func (c *FiberContext) Protocol() string
- func (c *FiberContext) Query(key string) string
- func (c *FiberContext) Redirect(location string, status ...int) error
- func (c *FiberContext) SendStatus(status int) error
- func (c *FiberContext) SendString(s string) error
- func (c *FiberContext) Set(key, value string)
- func (c *FiberContext) Status(status int) Context
- func (c *FiberContext) Underlying() *fiber.Ctx
- type FiberCookieHelper
- type FiberSession
- func (s *FiberSession) Delete(key string)
- func (s *FiberSession) Destroy() error
- func (s *FiberSession) Get(key string) interface{}
- func (s *FiberSession) ID() string
- func (s *FiberSession) Save() error
- func (s *FiberSession) Set(key string, value interface{})
- func (s *FiberSession) Underlying() *fibersession.Session
- type FiberSessionStore
- type ForwardedHeaders
- func (h ForwardedHeaders) BuildCallbackURL(c Context, authHost, loginPath, callbackParam string) string
- func (ForwardedHeaders) GetForwardedFor(c Context) string
- func (ForwardedHeaders) GetHost(c Context) string
- func (h ForwardedHeaders) GetMethod(c Context) string
- func (ForwardedHeaders) GetProto(c Context) string
- func (ForwardedHeaders) GetRealIP(c Context) string
- func (ForwardedHeaders) GetURI(c Context) string
- func (h ForwardedHeaders) IsDifferentDomain(c Context, authHost string) bool
- type Handler
- func (h *Handler) AddChecker(checker AuthChecker)
- func (h *Handler) Check(c Context, sess Session) (*AuthResult, error)
- func (h *Handler) GetConfig() *Config
- func (h *Handler) GetStepUpMatcher() *StepUpMatcher
- func (h *Handler) HandleNotAuthenticated(c Context) error
- func (h *Handler) HandleSessionError(c Context, err error) error
- func (h *Handler) HandleStepUpRequired(c Context) error
- func (h *Handler) SetAuthHeaders(c Context, result *AuthResult)
- type HeaderChecker
- type LogEvent
- type Logger
- type PasswordCheckFunc
- type PasswordChecker
- type Session
- type SessionChecker
- type SessionStore
- type StepUpMatcher
- type TranslateFunc
- type UserCheckFunc
- type UserInfo
- type UserInfoFunc
Constants ¶
const ( KeyAuthenticated = "authenticated" KeyUserID = "user_id" KeyUserMail = "user_mail" KeyUserPhone = "user_phone" KeyUserName = "user_name" KeyUserScope = "user_scope" KeyUserRole = "user_role" KeyUserAMR = "user_amr" KeyStepUpVerified = "step_up_verified" KeyAuthRefreshedAt = "auth_refreshed_at" )
SessionKeys defines common session key names used by ForwardAuth.
Variables ¶
var ( // Configuration errors ErrNoPasswordConfigured = errors.New("password authentication enabled but no passwords configured") ErrNoUserCheckFunc = errors.New("header authentication enabled but no user check function provided") ErrInvalidConfig = errors.New("invalid configuration") // Authentication errors ErrNotAuthenticated = errors.New("not authenticated") ErrInvalidPassword = errors.New("invalid password") ErrUserNotFound = errors.New("user not found") ErrSessionRequired = errors.New("session required") ErrStepUpRequired = errors.New("step-up authentication required") ErrSessionStoreError = errors.New("session store error") // HTTP status related ErrForbidden = errors.New("forbidden") )
Error definitions for ForwardAuth.
Functions ¶
func FiberCheckRoute ¶
func FiberCheckRoute(handler *Handler, store *fibersession.Store) fiber.Handler
FiberCheckRoute creates a Fiber handler for the ForwardAuth check route. This is the main entry point for Traefik/Nginx ForwardAuth integration.
func FiberMiddleware ¶
func FiberMiddleware(handler *Handler, store *fibersession.Store) fiber.Handler
FiberMiddleware creates a Fiber middleware for ForwardAuth.
func GetPreferredFormat ¶
GetPreferredFormat returns the preferred response format based on Accept header.
func IsHTMLRequest ¶
IsHTMLRequest checks if the request accepts HTML responses. It examines the Accept header to determine if the client expects HTML content.
Returns true if:
- Accept header is empty (defaults to HTML)
- Accept header contains "text/html"
- Accept header starts with "*/*" (accepts all types)
func IsJSONRequest ¶
IsJSONRequest checks if the request accepts JSON responses.
func IsXMLRequest ¶
IsXMLRequest checks if the request accepts XML responses.
func MergeScopesUnique ¶
MergeScopesUnique merges two scope slices and removes duplicates.
func NormalizeHost ¶
NormalizeHost removes port number from hostname for comparison.
func ParseScopesFromHeader ¶
ParseScopesFromHeader parses comma-separated scopes from a header value.
func ScopesContain ¶
ScopesContain checks if the scopes slice contains the target scope.
func SendErrorResponse ¶
SendErrorResponse sends an error response in the format preferred by the client. It automatically detects the best response format based on the Accept header:
- application/json -> JSON format with error object
- application/xml -> XML format with error element
- default -> plain text
Types ¶
type AuthChecker ¶
type AuthChecker interface {
// Check performs the authentication check and returns the result.
Check(c Context, sess Session) (*AuthResult, error)
// Priority returns the priority of this checker (lower = higher priority).
Priority() int
// Name returns the name of this checker.
Name() string
}
AuthChecker defines the interface for authentication checking.
type AuthHeaderBuilder ¶
type AuthHeaderBuilder struct {
// contains filtered or unexported fields
}
AuthHeaderBuilder builds authentication headers for downstream services.
func NewAuthHeaderBuilder ¶
func NewAuthHeaderBuilder(config *Config) *AuthHeaderBuilder
NewAuthHeaderBuilder creates a new AuthHeaderBuilder.
func (*AuthHeaderBuilder) BuildHeaders ¶
func (b *AuthHeaderBuilder) BuildHeaders(result *AuthResult) map[string]string
BuildHeaders builds the authentication headers from an AuthResult.
func (*AuthHeaderBuilder) SetHeaders ¶
func (b *AuthHeaderBuilder) SetHeaders(c Context, result *AuthResult)
SetHeaders sets the authentication headers on the context.
type AuthMethod ¶
type AuthMethod int
AuthMethod represents the authentication method used.
const ( AuthMethodNone AuthMethod = iota AuthMethodSession AuthMethodPassword AuthMethodHeader AuthMethodToken )
func (AuthMethod) String ¶
func (m AuthMethod) String() string
String returns the string representation of the auth method.
type AuthResult ¶
type AuthResult struct {
Authenticated bool
UserID string
Email string
Phone string
Name string // User display name (optional)
Scopes []string
Role string
AMR []string // Authentication Methods Reference
AuthMethod AuthMethod
NeedsRefresh bool
RefreshedAt time.Time
}
AuthResult contains the result of an authentication check.
type Config ¶
type Config struct {
// Session configuration
SessionEnabled bool
// Password authentication
PasswordEnabled bool
PasswordHeader string // Header name for password authentication (default: "Stargate-Password")
ValidPasswords []string // List of valid password hashes
PasswordAlgorithm string // Algorithm: "plaintext", "bcrypt", "argon2"
PasswordCheckFunc PasswordCheckFunc
PasswordNormalizer func(password string) string // Optional password normalizer
// Header-based authentication (e.g., Warden)
HeaderAuthEnabled bool
HeaderAuthUserPhone string // Header name for phone (default: "X-User-Phone")
HeaderAuthUserMail string // Header name for email (default: "X-User-Mail")
HeaderAuthCheckFunc UserCheckFunc
HeaderAuthGetInfoFunc UserInfoFunc
// Step-up authentication
StepUpEnabled bool
StepUpPaths []string // Glob patterns for paths requiring step-up auth
StepUpURL string // URL to redirect for step-up authentication (default: "/_step_up")
StepUpSessionKey string // Session key for step-up verified flag (default: "step_up_verified")
// Auth refresh
AuthRefreshEnabled bool
AuthRefreshInterval time.Duration // Interval between auth info refreshes (default: 5 minutes)
// Response configuration
UserHeaderName string // Header name for authenticated user (default: "X-Forwarded-User")
AuthUserHeader string // X-Auth-User header (default: "X-Auth-User")
AuthEmailHeader string // X-Auth-Email header (default: "X-Auth-Email")
AuthNameHeader string // X-Auth-Name header (default: "X-Auth-Name")
AuthScopesHeader string // X-Auth-Scopes header (default: "X-Auth-Scopes")
AuthRoleHeader string // X-Auth-Role header (default: "X-Auth-Role")
AuthAMRHeader string // X-Auth-AMR header (default: "X-Auth-AMR")
// Login redirect
AuthHost string // Host for authentication service
LoginPath string // Path to login page (default: "/_login")
CallbackParam string // Query parameter for callback URL (default: "callback")
// Error handling
ErrorHandler ErrorHandler
// i18n support
TranslateFunc TranslateFunc
// Logging
Logger Logger
}
Config defines the ForwardAuth handler configuration.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults.
func (*Config) ApplyDefaults ¶
func (c *Config) ApplyDefaults()
ApplyDefaults fills in default values for empty fields.
type Context ¶
type Context interface {
// Request information
Path() string
Method() string
Protocol() string
Hostname() string
Get(key string) string // Get request header
Query(key string) string
// Response methods
Set(key, value string) // Set response header
SendStatus(status int) error
Redirect(location string, status ...int) error
Status(status int) Context
JSON(v interface{}) error
SendString(s string) error
// Session/Locals
Locals(key string, value ...interface{}) interface{}
// Context
Context() context.Context
}
Context abstracts the HTTP context interface for framework independence.
type ErrorCode ¶
type ErrorCode string
ErrorCode represents an error code for API responses.
const ( ErrorCodeInvalidPassword ErrorCode = "invalid_password" ErrorCodeUserNotFound ErrorCode = "user_not_found" ErrorCodeSessionRequired ErrorCode = "session_required" ErrorCodeStepUpRequired ErrorCode = "step_up_required" ErrorCodeSessionError ErrorCode = "session_error" ErrorCodeInternalError ErrorCode = "internal_error" )
type ErrorHandler ¶
ErrorHandler handles authentication errors.
type ErrorResponse ¶
type ErrorResponse struct {
OK bool `json:"ok"`
Code ErrorCode `json:"code,omitempty"`
Message string `json:"message,omitempty"`
Status int `json:"status,omitempty"`
}
ErrorResponse represents an error response structure.
func NewErrorResponse ¶
func NewErrorResponse(code ErrorCode, message string, status int) *ErrorResponse
NewErrorResponse creates a new error response.
type FiberContext ¶
type FiberContext struct {
// contains filtered or unexported fields
}
FiberContext wraps a Fiber context to implement the Context interface.
func NewFiberContext ¶
func NewFiberContext(c *fiber.Ctx) *FiberContext
NewFiberContext creates a new FiberContext wrapper.
func (*FiberContext) Context ¶
func (c *FiberContext) Context() context.Context
Context returns the underlying context.Context.
func (*FiberContext) Get ¶
func (c *FiberContext) Get(key string) string
Get returns a request header value.
func (*FiberContext) Hostname ¶
func (c *FiberContext) Hostname() string
Hostname returns the request hostname.
func (*FiberContext) JSON ¶
func (c *FiberContext) JSON(v interface{}) error
JSON sends a JSON response.
func (*FiberContext) Locals ¶
func (c *FiberContext) Locals(key string, value ...interface{}) interface{}
Locals gets or sets a local value.
func (*FiberContext) Method ¶
func (c *FiberContext) Method() string
Method returns the request method.
func (*FiberContext) Protocol ¶
func (c *FiberContext) Protocol() string
Protocol returns the request protocol.
func (*FiberContext) Query ¶
func (c *FiberContext) Query(key string) string
Query returns a query parameter value.
func (*FiberContext) Redirect ¶
func (c *FiberContext) Redirect(location string, status ...int) error
Redirect redirects to the specified location.
func (*FiberContext) SendStatus ¶
func (c *FiberContext) SendStatus(status int) error
SendStatus sends a status code response.
func (*FiberContext) SendString ¶
func (c *FiberContext) SendString(s string) error
SendString sends a string response.
func (*FiberContext) Set ¶
func (c *FiberContext) Set(key, value string)
Set sets a response header.
func (*FiberContext) Status ¶
func (c *FiberContext) Status(status int) Context
Status sets the response status code.
func (*FiberContext) Underlying ¶
func (c *FiberContext) Underlying() *fiber.Ctx
Underlying returns the underlying fiber.Ctx.
type FiberCookieHelper ¶
type FiberCookieHelper struct {
// contains filtered or unexported fields
}
FiberCookieHelper provides cookie utilities for Fiber.
func NewFiberCookieHelper ¶
func NewFiberCookieHelper(cookieDomain string, secure bool) *FiberCookieHelper
NewFiberCookieHelper creates a new FiberCookieHelper.
func (*FiberCookieHelper) ClearCallbackCookie ¶
func (h *FiberCookieHelper) ClearCallbackCookie(c *fiber.Ctx, name string)
ClearCallbackCookie clears a callback cookie.
func (*FiberCookieHelper) GetCallbackCookie ¶
func (h *FiberCookieHelper) GetCallbackCookie(c *fiber.Ctx, name string) string
GetCallbackCookie retrieves a callback cookie value.
func (*FiberCookieHelper) SetCallbackCookie ¶
func (h *FiberCookieHelper) SetCallbackCookie(c *fiber.Ctx, name, value string, maxAge int)
SetCallbackCookie sets a callback cookie for cross-domain authentication.
type FiberSession ¶
type FiberSession struct {
// contains filtered or unexported fields
}
FiberSession wraps a Fiber session to implement the Session interface.
func NewFiberSession ¶
func NewFiberSession(sess *fibersession.Session) *FiberSession
NewFiberSession creates a new FiberSession wrapper.
func (*FiberSession) Delete ¶
func (s *FiberSession) Delete(key string)
Delete removes a session value.
func (*FiberSession) Get ¶
func (s *FiberSession) Get(key string) interface{}
Get returns a session value.
func (*FiberSession) Set ¶
func (s *FiberSession) Set(key string, value interface{})
Set sets a session value.
func (*FiberSession) Underlying ¶
func (s *FiberSession) Underlying() *fibersession.Session
Underlying returns the underlying fiber session.
type FiberSessionStore ¶
type FiberSessionStore struct {
// contains filtered or unexported fields
}
FiberSessionStore wraps a Fiber session store to implement the SessionStore interface.
func NewFiberSessionStore ¶
func NewFiberSessionStore(store *fibersession.Store) *FiberSessionStore
NewFiberSessionStore creates a new FiberSessionStore wrapper.
func (*FiberSessionStore) Get ¶
func (s *FiberSessionStore) Get(c Context) (Session, error)
Get retrieves the session for the given context.
func (*FiberSessionStore) Underlying ¶
func (s *FiberSessionStore) Underlying() *fibersession.Store
Underlying returns the underlying fiber session store.
type ForwardedHeaders ¶
type ForwardedHeaders struct{}
ForwardedHeaders provides utilities for working with X-Forwarded-* headers.
func (ForwardedHeaders) BuildCallbackURL ¶
func (h ForwardedHeaders) BuildCallbackURL(c Context, authHost, loginPath, callbackParam string) string
BuildCallbackURL constructs a callback URL for authentication redirects.
func (ForwardedHeaders) GetForwardedFor ¶
func (ForwardedHeaders) GetForwardedFor(c Context) string
GetForwardedFor returns the X-Forwarded-For header value.
func (ForwardedHeaders) GetHost ¶
func (ForwardedHeaders) GetHost(c Context) string
GetHost returns the forwarded hostname from the request. It prioritizes the X-Forwarded-Host header if present.
func (ForwardedHeaders) GetMethod ¶
func (h ForwardedHeaders) GetMethod(c Context) string
GetMethod returns the forwarded method from the request. It prioritizes the X-Forwarded-Method header if present.
func (ForwardedHeaders) GetProto ¶
func (ForwardedHeaders) GetProto(c Context) string
GetProto returns the forwarded protocol from the request. It prioritizes the X-Forwarded-Proto header if present.
func (ForwardedHeaders) GetRealIP ¶
func (ForwardedHeaders) GetRealIP(c Context) string
GetRealIP returns the X-Real-IP header value.
func (ForwardedHeaders) GetURI ¶
func (ForwardedHeaders) GetURI(c Context) string
GetURI returns the forwarded URI from the request. It prioritizes the X-Forwarded-Uri header if present.
func (ForwardedHeaders) IsDifferentDomain ¶
func (h ForwardedHeaders) IsDifferentDomain(c Context, authHost string) bool
IsDifferentDomain checks if the origin host is different from the auth host.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler is the main ForwardAuth handler.
func NewHandler ¶
NewHandler creates a new ForwardAuth handler.
func (*Handler) AddChecker ¶
func (h *Handler) AddChecker(checker AuthChecker)
AddChecker adds an authentication checker to the handler.
func (*Handler) Check ¶
func (h *Handler) Check(c Context, sess Session) (*AuthResult, error)
Check performs the full authentication check.
func (*Handler) GetStepUpMatcher ¶
func (h *Handler) GetStepUpMatcher() *StepUpMatcher
GetStepUpMatcher returns the step-up matcher.
func (*Handler) HandleNotAuthenticated ¶
HandleNotAuthenticated handles unauthenticated requests. For HTML requests, it redirects to the login page. For API requests, it returns a 401 error response.
func (*Handler) HandleSessionError ¶
HandleSessionError handles session store errors.
func (*Handler) HandleStepUpRequired ¶
HandleStepUpRequired handles requests that require step-up authentication.
func (*Handler) SetAuthHeaders ¶
func (h *Handler) SetAuthHeaders(c Context, result *AuthResult)
SetAuthHeaders sets the authentication headers on the context.
type HeaderChecker ¶
type HeaderChecker struct {
// contains filtered or unexported fields
}
HeaderChecker implements header-based authentication (e.g., Warden).
func NewHeaderChecker ¶
func NewHeaderChecker(config *Config) *HeaderChecker
NewHeaderChecker creates a new header checker.
func (*HeaderChecker) Check ¶
func (c *HeaderChecker) Check(ctx Context, sess Session) (*AuthResult, error)
Check implements AuthChecker.
func (*HeaderChecker) Priority ¶
func (c *HeaderChecker) Priority() int
Priority implements AuthChecker.
type LogEvent ¶
type LogEvent interface {
Str(key, val string) LogEvent
Bool(key string, val bool) LogEvent
Int(key string, val int) LogEvent
Int64(key string, val int64) LogEvent
Dur(key string, val time.Duration) LogEvent
Err(err error) LogEvent
Msg(msg string)
}
LogEvent represents a logging event.
type PasswordCheckFunc ¶
PasswordCheckFunc is a function that validates a password.
type PasswordChecker ¶
type PasswordChecker struct {
// contains filtered or unexported fields
}
PasswordChecker implements password-based authentication.
func NewPasswordChecker ¶
func NewPasswordChecker(config *Config) *PasswordChecker
NewPasswordChecker creates a new password checker.
func (*PasswordChecker) Check ¶
func (c *PasswordChecker) Check(ctx Context, sess Session) (*AuthResult, error)
Check implements AuthChecker.
func (*PasswordChecker) Priority ¶
func (c *PasswordChecker) Priority() int
Priority implements AuthChecker.
type Session ¶
type Session interface {
Get(key string) interface{}
Set(key string, value interface{})
Delete(key string)
Save() error
Destroy() error
ID() string
}
Session abstracts the session interface.
type SessionChecker ¶
type SessionChecker struct {
// contains filtered or unexported fields
}
SessionChecker implements session-based authentication.
func NewSessionChecker ¶
func NewSessionChecker(config *Config) *SessionChecker
NewSessionChecker creates a new session checker.
func (*SessionChecker) Check ¶
func (c *SessionChecker) Check(ctx Context, sess Session) (*AuthResult, error)
Check implements AuthChecker.
func (*SessionChecker) Priority ¶
func (c *SessionChecker) Priority() int
Priority implements AuthChecker.
type SessionStore ¶
SessionStore abstracts the session store interface.
type StepUpMatcher ¶
type StepUpMatcher struct {
// contains filtered or unexported fields
}
StepUpMatcher handles step-up authentication path matching.
func NewStepUpMatcher ¶
func NewStepUpMatcher(enabled bool, pathPatterns []string) *StepUpMatcher
NewStepUpMatcher creates a new StepUpMatcher from the given path patterns. Patterns support glob-style wildcards: * matches any characters, ? matches a single character.
func (*StepUpMatcher) IsEnabled ¶
func (m *StepUpMatcher) IsEnabled() bool
IsEnabled returns whether step-up matching is enabled.
func (*StepUpMatcher) PatternCount ¶
func (m *StepUpMatcher) PatternCount() int
PatternCount returns the number of configured patterns.
func (*StepUpMatcher) RequiresStepUp ¶
func (m *StepUpMatcher) RequiresStepUp(path string) bool
RequiresStepUp checks if the given path requires step-up authentication.
type TranslateFunc ¶
TranslateFunc translates messages based on context locale.
type UserCheckFunc ¶
UserCheckFunc is a function that checks if a user exists in the allow list.
type UserInfo ¶
type UserInfo struct {
UserID string
Email string
Phone string
Name string // User display name (optional)
Scopes []string
Role string
Status string
Metadata map[string]interface{}
}
UserInfo contains user information from an external source.
type UserInfoFunc ¶
UserInfoFunc is a function that retrieves user information.