forwardauth

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 6, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

README

forwardauth-kit

Go Reference Go Report Card License codecov

中文文档

A Go library providing ForwardAuth middleware for reverse proxy authentication. Supports multiple authentication methods and integrates with session management for use with Traefik, Nginx, and other reverse proxies.

Features

  • Multiple Authentication Methods: Password, Header-based (Warden), and Session authentication
  • Priority-based Checker Chain: Configurable authentication method priority
  • Step-up Authentication: Support for sensitive path protection with additional authentication
  • Auth Refresh: Automatic refresh of user authorization information
  • Flexible Header Mapping: Customizable authentication response headers
  • Framework Agnostic: Core logic is framework-independent with Fiber adapter included
  • Cross-domain Support: Cookie utilities for cross-domain authentication flows

Installation

go get github.com/soulteary/forwardauth-kit

Quick Start

Basic Fiber Integration
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/session"
    forwardauth "github.com/soulteary/forwardauth-kit"
)

func main() {
    app := fiber.New()
    store := session.New()

    // Configure ForwardAuth
    config := forwardauth.Config{
        SessionEnabled: true,
        AuthHost:       "auth.example.com",
        LoginPath:      "/_login",
    }

    handler := forwardauth.NewHandler(&config)

    // Register ForwardAuth check route
    app.All("/_auth", forwardauth.FiberCheckRoute(handler, store))

    app.Listen(":3000")
}
Password Authentication
config := forwardauth.Config{
    PasswordEnabled: true,
    PasswordHeader:  "Stargate-Password",
    ValidPasswords:  []string{"HASHED_PASSWORD_1", "HASHED_PASSWORD_2"},
}

handler := forwardauth.NewHandler(&config)
Header-based Authentication (Warden Integration)
config := forwardauth.Config{
    HeaderAuthEnabled:   true,
    HeaderAuthUserPhone: "X-User-Phone",
    HeaderAuthUserMail:  "X-User-Mail",
    HeaderAuthCheckFunc: func(phone, mail string) bool {
        // Check if user exists in allow list
        return wardenClient.CheckUserInList(phone, mail)
    },
    HeaderAuthGetInfoFunc: func(phone, mail string) *forwardauth.UserInfo {
        // Get full user info for headers
        user := wardenClient.GetUser(phone, mail)
        if user == nil {
            return nil
        }
        return &forwardauth.UserInfo{
            UserID: user.ID,
            Email:  user.Email,
            Phone:  user.Phone,
            Scopes: user.Scopes,
            Role:   user.Role,
        }
    },
}

handler := forwardauth.NewHandler(&config)
Step-up Authentication
config := forwardauth.Config{
    SessionEnabled:   true,
    StepUpEnabled:    true,
    StepUpPaths:      []string{"/admin/*", "/settings/security"},
    StepUpURL:        "/_step_up",
    StepUpSessionKey: "step_up_verified",
}

handler := forwardauth.NewHandler(&config)
Auth Info Refresh
config := forwardauth.Config{
    SessionEnabled:      true,
    HeaderAuthEnabled:   true,
    AuthRefreshEnabled:  true,
    AuthRefreshInterval: 5 * time.Minute,
    HeaderAuthGetInfoFunc: func(phone, mail string) *forwardauth.UserInfo {
        // Refresh user info periodically
        return getUserFromWarden(phone, mail)
    },
}

handler := forwardauth.NewHandler(&config)

Configuration

Option Type Default Description
SessionEnabled bool true Enable session-based authentication
PasswordEnabled bool false Enable password header authentication
PasswordHeader string "Stargate-Password" Header name for password
ValidPasswords []string - List of valid password hashes
PasswordCheckFunc func - Custom password validation function
HeaderAuthEnabled bool false Enable header-based authentication
HeaderAuthUserPhone string "X-User-Phone" Header name for phone
HeaderAuthUserMail string "X-User-Mail" Header name for email
HeaderAuthCheckFunc func - User existence check function
HeaderAuthGetInfoFunc func - User info retrieval function
StepUpEnabled bool false Enable step-up authentication
StepUpPaths []string - Glob patterns for protected paths
StepUpURL string "/_step_up" Step-up verification URL
StepUpSessionKey string "step_up_verified" Session key for step-up flag
AuthRefreshEnabled bool false Enable auth info refresh
AuthRefreshInterval Duration 5m Interval between refreshes
UserHeaderName string "X-Forwarded-User" Primary user header
AuthUserHeader string "X-Auth-User" User ID header
AuthEmailHeader string "X-Auth-Email" Email header
AuthScopesHeader string "X-Auth-Scopes" Scopes header (comma-separated)
AuthRoleHeader string "X-Auth-Role" Role header
AuthAMRHeader string "X-Auth-AMR" AMR header (comma-separated)
AuthHost string - Authentication service host
LoginPath string "/_login" Login page path
CallbackParam string "callback" Callback query parameter

Response Headers

On successful authentication, the following headers are set:

Header Description Example
X-Forwarded-User User identifier or "authenticated" user-123
X-Auth-User User ID user-123
X-Auth-Email User email user@example.com
X-Auth-Scopes Comma-separated scopes read,write,admin
X-Auth-Role User role admin
X-Auth-AMR Authentication methods used otp,mfa

Custom Checkers

Implement the AuthChecker interface to add custom authentication methods:

type CustomChecker struct {
    config *forwardauth.Config
}

func (c *CustomChecker) Check(ctx forwardauth.Context, sess forwardauth.Session) (*forwardauth.AuthResult, error) {
    // Custom authentication logic
    token := ctx.Get("Authorization")
    if token == "" {
        return nil, nil // Skip to next checker
    }

    // Validate token...
    if valid {
        return &forwardauth.AuthResult{
            Authenticated: true,
            UserID:        "user-123",
            AuthMethod:    forwardauth.AuthMethodToken,
        }, nil
    }
    return nil, forwardauth.ErrNotAuthenticated
}

func (c *CustomChecker) Priority() int { return 5 } // Higher priority than password (10)
func (c *CustomChecker) Name() string { return "custom" }

// Add to handler
handler.AddChecker(&CustomChecker{config: &config})

Traefik Configuration

http:
  middlewares:
    auth:
      forwardAuth:
        address: "http://auth-service:3000/_auth"
        trustForwardHeader: true
        authResponseHeaders:
          - "X-Forwarded-User"
          - "X-Auth-User"
          - "X-Auth-Email"
          - "X-Auth-Scopes"
          - "X-Auth-Role"
          - "X-Auth-AMR"

  routers:
    my-router:
      rule: "Host(`app.example.com`)"
      middlewares:
        - auth
      service: my-service

Nginx Configuration

location / {
    auth_request /_auth;
    auth_request_set $auth_user $upstream_http_x_auth_user;
    auth_request_set $auth_email $upstream_http_x_auth_email;
    
    proxy_set_header X-Auth-User $auth_user;
    proxy_set_header X-Auth-Email $auth_email;
    proxy_pass http://backend;
}

location = /_auth {
    internal;
    proxy_pass http://auth-service:3000/_auth;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Uri $request_uri;
}

License

MIT License

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

View Source
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

View Source
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
	ErrUnauthorized = errors.New("unauthorized")
	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

func GetPreferredFormat(c Context) string

GetPreferredFormat returns the preferred response format based on Accept header.

func IsHTMLRequest

func IsHTMLRequest(c Context) bool

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

func IsJSONRequest(c Context) bool

IsJSONRequest checks if the request accepts JSON responses.

func IsXMLRequest

func IsXMLRequest(c Context) bool

IsXMLRequest checks if the request accepts XML responses.

func MergeScopesUnique

func MergeScopesUnique(a, b []string) []string

MergeScopesUnique merges two scope slices and removes duplicates.

func NormalizeHost

func NormalizeHost(host string) string

NormalizeHost removes port number from hostname for comparison.

func ParseScopesFromHeader

func ParseScopesFromHeader(header string) []string

ParseScopesFromHeader parses comma-separated scopes from a header value.

func ScopesContain

func ScopesContain(scopes []string, target string) bool

ScopesContain checks if the scopes slice contains the target scope.

func SendErrorResponse

func SendErrorResponse(c Context, statusCode int, message string) error

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.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid.

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 (
	ErrorCodeUnauthorized    ErrorCode = "unauthorized"
	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

type ErrorHandler func(c Context, statusCode int, message string) error

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) Path

func (c *FiberContext) Path() string

Path returns the request path.

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) Destroy

func (s *FiberSession) Destroy() error

Destroy destroys the session.

func (*FiberSession) Get

func (s *FiberSession) Get(key string) interface{}

Get returns a session value.

func (*FiberSession) ID

func (s *FiberSession) ID() string

ID returns the session ID.

func (*FiberSession) Save

func (s *FiberSession) Save() error

Save saves the session.

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

func NewHandler(config *Config) *Handler

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) GetConfig

func (h *Handler) GetConfig() *Config

GetConfig returns the handler configuration.

func (*Handler) GetStepUpMatcher

func (h *Handler) GetStepUpMatcher() *StepUpMatcher

GetStepUpMatcher returns the step-up matcher.

func (*Handler) HandleNotAuthenticated

func (h *Handler) HandleNotAuthenticated(c Context) error

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

func (h *Handler) HandleSessionError(c Context, err error) error

HandleSessionError handles session store errors.

func (*Handler) HandleStepUpRequired

func (h *Handler) HandleStepUpRequired(c Context) error

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) Name

func (c *HeaderChecker) Name() string

Name 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 Logger

type Logger interface {
	Debug() LogEvent
	Info() LogEvent
	Warn() LogEvent
	Error() LogEvent
}

Logger interface for logging.

type PasswordCheckFunc

type PasswordCheckFunc func(password string) bool

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) Name

func (c *PasswordChecker) Name() string

Name 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) Name

func (c *SessionChecker) Name() string

Name implements AuthChecker.

func (*SessionChecker) Priority

func (c *SessionChecker) Priority() int

Priority implements AuthChecker.

type SessionStore

type SessionStore interface {
	Get(c Context) (Session, error)
}

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

type TranslateFunc func(c Context, key string) string

TranslateFunc translates messages based on context locale.

type UserCheckFunc

type UserCheckFunc func(phone, mail string) bool

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.

func (*UserInfo) IsActive

func (u *UserInfo) IsActive() bool

IsActive returns whether the user is active.

type UserInfoFunc

type UserInfoFunc func(phone, mail string) *UserInfo

UserInfoFunc is a function that retrieves user information.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL