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
- func NewProtectedResourceHandler(meta *ProtectedResourceMetadata) http.Handler
- 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
- type ProtectedResourceMetadata
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
func NewProtectedResourceHandler ¶ added in v0.0.55
func NewProtectedResourceHandler(meta *ProtectedResourceMetadata) http.Handler
NewProtectedResourceHandler returns an http.Handler that serves the Protected Resource Metadata JSON at GET /.well-known/oauth-protected-resource.
The handler:
- Responds to GET only (405 for other methods)
- Sets Content-Type: application/json
- Sets Cache-Control: public, max-age=<CacheMaxAge>
- Serializes the metadata as JSON with omitempty on optional fields
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
type ProtectedResourceMetadata ¶ added in v0.0.55
type ProtectedResourceMetadata struct {
// Resource is the resource server's identifier (its base URL).
// REQUIRED per RFC 9728 §3.
Resource string `json:"resource"`
// AuthorizationServers lists the authorization servers that the resource
// server trusts to issue tokens. REQUIRED per RFC 9728 §3.
AuthorizationServers []string `json:"authorization_servers"`
// ScopesSupported lists the OAuth 2.0 scopes that this resource server
// understands. Optional.
ScopesSupported []string `json:"scopes_supported,omitempty"`
// TokenFormatsSupported lists the token formats accepted (e.g., "jwt").
// Optional.
TokenFormatsSupported []string `json:"token_formats_supported,omitempty"`
// SigningAlgsSupported lists the JWS signing algorithms the resource server
// supports for validating tokens (e.g., "RS256", "ES256", "HS256").
// Optional.
SigningAlgsSupported []string `json:"resource_signing_alg_values_supported,omitempty"`
// DocumentationURI points to human-readable documentation for the resource
// server's API. Optional.
DocumentationURI string `json:"resource_documentation,omitempty"`
// IntrospectionEndpoint is the URL of the token introspection endpoint
// (RFC 7662) that can be used to validate tokens for this resource.
// Optional — included when the resource server supports introspection.
IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"`
// CacheMaxAge controls the Cache-Control max-age header in seconds.
// Defaults to 3600 (1 hour) if zero. Not serialized to JSON.
CacheMaxAge int `json:"-"`
}
ProtectedResourceMetadata describes an OAuth 2.0 Protected Resource per RFC 9728. Resource servers serve this at GET /.well-known/oauth-protected-resource so clients can auto-discover which authorization servers are trusted, what scopes are supported, what token formats are accepted, and which signing algorithms are used.
Required fields: Resource and AuthorizationServers. All other fields are optional and omitted from JSON when empty.