Documentation
¶
Index ¶
- func GetAuthTypeFromAPIContext(ctx context.Context) string
- func GetCustomClaimsFromContext(ctx context.Context) map[string]any
- func GetScopesFromAPIContext(ctx context.Context) []string
- func GetUserIDFromAPIContext(ctx context.Context) string
- type APIAuth
- func (a *APIAuth) CreateAccessToken(userID string, scopes []string) (string, int64, error)
- func (a *APIAuth) HandleAPIKeys(w http.ResponseWriter, r *http.Request)
- func (a *APIAuth) HandleListSessions(w http.ResponseWriter, r *http.Request)
- func (a *APIAuth) HandleLogout(w http.ResponseWriter, r *http.Request)
- func (a *APIAuth) HandleLogoutAll(w http.ResponseWriter, r *http.Request)
- func (a *APIAuth) HandleRevokeAPIKey(w http.ResponseWriter, r *http.Request)
- func (a *APIAuth) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (a *APIAuth) ValidateAccessToken(tokenString string) (userID string, scopes []string, err error)
- func (a *APIAuth) ValidateAccessTokenFull(tokenString string) (userID string, scopes []string, customClaims map[string]any, err error)
- func (a *APIAuth) VerifyTokenFunc() func(tokenString string) (userID string, token any, err error)
- type APIMiddleware
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetAuthTypeFromAPIContext ¶
GetAuthTypeFromAPIContext retrieves the auth type ("jwt" or "api_key") from context
func GetCustomClaimsFromContext ¶
GetCustomClaimsFromContext retrieves the custom (non-standard) JWT claims from context. Returns nil if no custom claims are present (e.g., API key auth or no token).
func GetScopesFromAPIContext ¶
GetScopesFromAPIContext retrieves the granted scopes from the API middleware context
func GetUserIDFromAPIContext ¶
GetUserIDFromAPIContext retrieves the user ID from the API middleware context
Types ¶
type APIAuth ¶
type APIAuth struct {
// Stores
RefreshTokenStore core.RefreshTokenStore
APIKeyStore core.APIKeyStore
// JWT configuration
JWTSecretKey string // Secret key for signing JWTs (HMAC)
JWTIssuer string // Issuer claim (e.g., "myapp")
JWTAudience string // Audience claim (e.g., "api")
JWTSigningAlg string // Signing algorithm (defaults to HS256)
// Asymmetric JWT keys (optional — when set, these take precedence over JWTSecretKey)
JWTSigningKey any // crypto.PrivateKey (*rsa.PrivateKey or *ecdsa.PrivateKey) for signing
JWTVerifyKey any // crypto.PublicKey (*rsa.PublicKey or *ecdsa.PublicKey) for verification
// Token configuration
AccessTokenExpiry time.Duration // Defaults to 15 minutes
RefreshTokenExpiry time.Duration // Defaults to 7 days
// Callbacks
ValidateCredentials core.CredentialsValidator // Validates username/password
GetUserScopes core.GetUserScopesFunc // Returns allowed scopes for a user
OnLoginSuccess func(userID string, r *http.Request) // Optional: for logging/analytics
OnLoginFailure func(username string, r *http.Request, err error) // Optional: for logging/analytics
// CustomClaimsFunc is called during token creation to inject additional claims
// into the JWT (e.g., client_id, max_rooms for relay-scoped tokens).
// Standard claims (sub, iss, aud, exp, iat, type, scopes) cannot be overridden.
// If nil, no custom claims are added (backwards-compatible).
CustomClaimsFunc func(userID string, scopes []string) (map[string]any, error)
// Rate limiting (optional)
RateLimiter core.RateLimiter
// Blacklist enables immediate access token revocation. When set,
// ValidateAccessToken checks the blacklist after signature verification.
// Tokens include a jti (JWT ID) claim for blacklist lookup.
// If nil, tokens are validated by signature + expiry only (stateless).
Blacklist core.TokenBlacklist
}
APIAuth handles API token-based authentication
func (*APIAuth) CreateAccessToken ¶
CreateAccessToken creates a signed JWT access token. If CustomClaimsFunc is set, its returned claims are merged into the token (standard claims cannot be overridden).
func (*APIAuth) HandleAPIKeys ¶
func (a *APIAuth) HandleAPIKeys(w http.ResponseWriter, r *http.Request)
HandleAPIKeys handles API key management (GET=list, POST=create) Requires authentication (userID must be in request context)
func (*APIAuth) HandleListSessions ¶
func (a *APIAuth) HandleListSessions(w http.ResponseWriter, r *http.Request)
HandleListSessions handles GET /api/sessions - lists active sessions for the user Requires authentication (userID must be in request context)
func (*APIAuth) HandleLogout ¶
func (a *APIAuth) HandleLogout(w http.ResponseWriter, r *http.Request)
HandleLogout handles POST /api/logout - revokes a refresh token
func (*APIAuth) HandleLogoutAll ¶
func (a *APIAuth) HandleLogoutAll(w http.ResponseWriter, r *http.Request)
HandleLogoutAll handles POST /api/logout-all - revokes all refresh tokens for the user Requires authentication (userID must be in request context)
func (*APIAuth) HandleRevokeAPIKey ¶
func (a *APIAuth) HandleRevokeAPIKey(w http.ResponseWriter, r *http.Request)
HandleRevokeAPIKey handles DELETE /api/keys/:id - revokes an API key Requires authentication (userID must be in request context)
func (*APIAuth) ServeHTTP ¶
func (a *APIAuth) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP handles the /api/login endpoint
func (*APIAuth) ValidateAccessToken ¶
func (a *APIAuth) ValidateAccessToken(tokenString string) (userID string, scopes []string, err error)
ValidateAccessToken validates a JWT access token and returns the claims
func (*APIAuth) ValidateAccessTokenFull ¶
func (a *APIAuth) ValidateAccessTokenFull(tokenString string) (userID string, scopes []string, customClaims map[string]any, err error)
ValidateAccessTokenFull validates a JWT access token and returns the standard claims plus any custom claims (non-standard keys) as a separate map.
func (*APIAuth) VerifyTokenFunc ¶
VerifyTokenFunc returns a function that can be used as Middleware.VerifyToken. This allows the Middleware to validate Bearer tokens using the APIAuth's JWT configuration.
type APIMiddleware ¶
type APIMiddleware struct {
// JWT validation (uses same config as APIAuth)
JWTSecretKey string
JWTIssuer string
JWTAudience string
JWTSigningAlg string
// KeyStore for multi-tenant JWT validation. When set, the middleware uses
// GetKeyByKid (for tokens with kid header) or GetKey (for client_id claim).
// When nil, falls back to JWTSecretKey (single-tenant, backwards-compatible).
KeyStore keys.KeyLookup
// API key validation (optional)
APIKeyStore core.APIKeyStore
// Token header configuration
AuthHeader string // Defaults to "Authorization"
// TokenQueryParam is the query parameter name to check for a token as fallback
// when the Authorization header is missing (e.g., "token" for ?token=...).
// Empty string disables query param extraction (default).
TokenQueryParam string
// Error handling
OnAuthError func(w http.ResponseWriter, r *http.Request, err error)
// Blacklist enables immediate access token revocation. When set,
// validateJWT checks the blacklist after signature verification.
// If nil, no revocation check (stateless validation only).
Blacklist core.TokenBlacklist
}
APIMiddleware provides middleware for validating API tokens
func (*APIMiddleware) Optional ¶
func (m *APIMiddleware) Optional(next http.Handler) http.Handler
Optional middleware allows requests without auth but sets user info if present
func (*APIMiddleware) RequireScopes ¶
RequireScopes middleware ensures the authenticated user has all required scopes
func (*APIMiddleware) ValidateToken ¶
func (m *APIMiddleware) ValidateToken(next http.Handler) http.Handler
ValidateToken middleware validates Bearer tokens (JWT or API key) and sets user info in context