Documentation
¶
Index ¶
- Variables
- func NewExtension(opts ...ConfigOption) forge.Extension
- func NewExtensionWithConfig(config Config) forge.Extension
- func WithContext(ctx context.Context, authCtx *AuthContext) context.Context
- type AuthContext
- func FromContext(ctx context.Context) (*AuthContext, bool)
- func GetAuthContext(ctx forge.Context) (*AuthContext, bool)
- func GetAuthContextFromStdContext(ctx context.Context) (*AuthContext, bool)
- func MustFromContext(ctx context.Context) *AuthContext
- func MustGetAuthContext(ctx forge.Context) *AuthContext
- type AuthProvider
- type Config
- type ConfigOption
- type Extension
- type OAuthFlow
- type OAuthFlows
- type ProviderConfig
- type ProviderFunc
- type Registry
- type SecurityScheme
- type SecuritySchemeType
Constants ¶
This section is empty.
Variables ¶
var ( // ErrProviderNotFound is returned when a provider is not found. ErrProviderNotFound = errors.New("auth provider not found") // ErrProviderExists is returned when a provider already exists. ErrProviderExists = errors.New("auth provider already exists") // ErrInvalidConfiguration is returned when configuration is invalid. ErrInvalidConfiguration = errors.New("invalid auth configuration") // ErrMissingCredentials is returned when credentials are missing. ErrMissingCredentials = errors.New("missing authentication credentials") // ErrInvalidCredentials is returned when credentials are invalid. ErrInvalidCredentials = errors.New("invalid credentials") // ErrInsufficientScopes is returned when required scopes are missing. ErrInsufficientScopes = errors.New("insufficient scopes") // ErrAuthenticationFailed is returned when authentication fails. ErrAuthenticationFailed = errors.New("authentication failed") // ErrAuthorizationFailed is returned when authorization fails. ErrAuthorizationFailed = errors.New("authorization failed") // ErrTokenExpired is returned when a token has expired. ErrTokenExpired = errors.New("token expired") // ErrTokenInvalid is returned when a token is invalid. ErrTokenInvalid = errors.New("invalid token") )
Functions ¶
func NewExtension ¶
func NewExtension(opts ...ConfigOption) forge.Extension
NewExtension creates a new auth extension with functional options.
Example:
auth.NewExtension(
auth.WithEnabled(true),
auth.WithDefaultProvider("jwt"),
)
func NewExtensionWithConfig ¶
NewExtensionWithConfig creates a new auth extension with a complete config. This is for backward compatibility or when config is fully known at initialization.
func WithContext ¶
func WithContext(ctx context.Context, authCtx *AuthContext) context.Context
WithContext adds the AuthContext to a context.
Types ¶
type AuthContext ¶
type AuthContext struct {
// Subject is the authenticated entity (user ID, service ID, etc.)
Subject string
// Claims holds additional authentication claims (roles, permissions, etc.)
Claims map[string]any
// Scopes holds OAuth2 scopes or permission strings
Scopes []string
// Metadata holds provider-specific metadata
Metadata map[string]any
// Data holds additional data from the authenticated provider
Data any
// ProviderName identifies which auth provider authenticated this request
ProviderName string
}
AuthContext holds authenticated user/service information. This is stored in the request context after successful authentication.
func FromContext ¶
func FromContext(ctx context.Context) (*AuthContext, bool)
FromContext retrieves the AuthContext from the request context. Returns the auth context and true if found, nil and false otherwise.
func GetAuthContext ¶ added in v0.5.0
func GetAuthContext(ctx forge.Context) (*AuthContext, bool)
GetAuthContext retrieves the AuthContext from forge.Context. Returns the auth context and true if found, nil and false otherwise.
func GetAuthContextFromStdContext ¶ added in v0.5.0
func GetAuthContextFromStdContext(ctx context.Context) (*AuthContext, bool)
GetAuthContextFromStdContext retrieves AuthContext from standard context.Context. This is for backward compatibility with code that uses standard context. For new code using forge.Context, use GetAuthContext instead.
func MustFromContext ¶
func MustFromContext(ctx context.Context) *AuthContext
MustFromContext retrieves the AuthContext or panics. Use this only when you're certain the context contains auth information (e.g., after auth middleware has run).
func MustGetAuthContext ¶ added in v0.5.0
func MustGetAuthContext(ctx forge.Context) *AuthContext
MustGetAuthContext retrieves the AuthContext from forge.Context or panics. Use this only when you're certain the context contains auth information (e.g., after auth middleware has run).
func (*AuthContext) GetClaim ¶
func (a *AuthContext) GetClaim(key string) (any, bool)
GetClaim retrieves a claim by key.
func (*AuthContext) GetClaimString ¶
func (a *AuthContext) GetClaimString(key string) (string, bool)
GetClaimString retrieves a string claim.
func (*AuthContext) HasScope ¶
func (a *AuthContext) HasScope(scope string) bool
HasScope checks if the auth context has a specific scope.
func (*AuthContext) HasScopes ¶
func (a *AuthContext) HasScopes(scopes ...string) bool
HasScopes checks if the auth context has all specified scopes.
type AuthProvider ¶
type AuthProvider interface {
// Name returns the unique name/ID of this auth provider.
// This name is used to reference the provider in route/group options.
Name() string
// Type returns the OpenAPI security scheme type
Type() SecuritySchemeType
// Authenticate validates the request and returns the authenticated subject.
// Returns the auth context (user, claims, etc.) or an error.
// The provider can access services from the DI container via closures.
Authenticate(ctx context.Context, r *http.Request) (*AuthContext, error)
// OpenAPIScheme returns the OpenAPI security scheme definition.
// This is used to automatically generate OpenAPI security documentation.
OpenAPIScheme() SecurityScheme
// Middleware returns HTTP middleware for this provider.
// The middleware is automatically applied when the provider is used.
Middleware() forge.Middleware
}
AuthProvider defines the interface for authentication providers. Implementations can access the DI container through closures or context to retrieve services needed for authentication (database, cache, etc.).
type Config ¶
type Config struct {
// Enabled determines if auth extension is enabled
Enabled bool
// Providers holds provider-specific configurations
Providers []ProviderConfig
// DefaultProvider is the default provider name to use
DefaultProvider string
// RequireConfig requires config from ConfigManager
RequireConfig bool
}
Config holds auth extension configuration.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns the default auth configuration.
type ConfigOption ¶
type ConfigOption func(*Config)
ConfigOption configures the auth extension.
func WithDefaultProvider ¶
func WithDefaultProvider(name string) ConfigOption
WithDefaultProvider sets the default provider.
func WithEnabled ¶
func WithEnabled(enabled bool) ConfigOption
WithEnabled sets whether auth is enabled.
func WithProviders ¶
func WithProviders(providers ...ProviderConfig) ConfigOption
WithProviders sets the provider configurations.
func WithRequireConfig ¶
func WithRequireConfig(require bool) ConfigOption
WithRequireConfig requires config from ConfigManager.
type Extension ¶
type Extension struct {
*forge.BaseExtension
// contains filtered or unexported fields
}
Extension implements forge.Extension for authentication and authorization. It provides a registry for managing auth providers and automatically integrates with the router for OpenAPI security scheme generation.
func (*Extension) Register ¶
Register registers the auth extension with the app. It creates and registers the auth provider registry as a singleton service.
func (*Extension) Registry ¶
Registry returns the auth provider registry. This allows external code to register custom auth providers.
type ProviderConfig ¶
type ProviderConfig struct {
Name string
Type string
Enabled bool
Description string
Config map[string]any
}
ProviderConfig holds configuration for a single auth provider.
type ProviderFunc ¶
ProviderFunc is a function adapter for simple auth providers.
type Registry ¶
type Registry interface {
// Register registers an auth provider
Register(provider AuthProvider) error
// Unregister removes a provider by name
Unregister(name string) error
// Get retrieves a provider by name
Get(name string) (AuthProvider, error)
// Has checks if a provider exists
Has(name string) bool
// List returns all registered provider names
List() []string
// Middleware creates combined middleware for multiple providers.
// When multiple providers are specified, they are tried in order (OR logic).
// Authentication succeeds if ANY provider succeeds.
Middleware(providerNames ...string) forge.Middleware
// MiddlewareAnd creates middleware requiring ALL providers to succeed (AND logic).
MiddlewareAnd(providerNames ...string) forge.Middleware
// MiddlewareWithScopes creates middleware with required scopes
MiddlewareWithScopes(providerName string, scopes ...string) forge.Middleware
// OpenAPISchemes returns all security schemes for OpenAPI generation
OpenAPISchemes() map[string]SecurityScheme
}
Registry manages authentication providers. It provides thread-safe registration and retrieval of auth providers, and can create middleware that chains multiple providers.
type SecurityScheme ¶
type SecurityScheme = shared.SecurityScheme
SecurityScheme represents an OpenAPI security scheme definition We use the shared type to ensure compatibility with OpenAPI generation.
type SecuritySchemeType ¶
type SecuritySchemeType string
SecuritySchemeType represents OpenAPI 3.1 security scheme types.
const ( SecurityTypeAPIKey SecuritySchemeType = "apiKey" SecurityTypeHTTP SecuritySchemeType = "http" SecurityTypeOAuth2 SecuritySchemeType = "oauth2" SecurityTypeOpenIDConnect SecuritySchemeType = "openIdConnect" SecurityTypeMutualTLS SecuritySchemeType = "mutualTLS" )