Documentation
¶
Overview ¶
Package auth provides HTTP and gRPC authentication middleware with API key and JWT validation. It supports extracting user/service identity from requests and propagating authentication context through context.Context.
Example usage with API key:
// HTTP middleware
validKeys := []string{"key1", "key2"}
http.Handle("/api/", auth.APIKeyMiddleware(validKeys)(handler))
// gRPC interceptor
server := grpc.NewServer(
grpc.UnaryInterceptor(auth.APIKeyUnaryInterceptor(validKeys)),
)
Example usage with JWT:
publicKey, _ := auth.LoadPublicKeyFromPEM(pemBytes)
middleware := auth.JWTMiddleware(publicKey, "issuer", "audience")
http.Handle("/api/", middleware(handler))
Index ¶
- func APIKeyMiddleware(validKeys []string) func(http.Handler) http.Handler
- func APIKeyStreamInterceptor(validKeys []string) grpc.StreamServerInterceptor
- func APIKeyUnaryInterceptor(validKeys []string) grpc.UnaryServerInterceptor
- func JWTMiddleware(config JWTConfig) func(http.Handler) http.Handler
- func JWTStreamInterceptor(config JWTConfig) grpc.StreamServerInterceptor
- func JWTUnaryInterceptor(config JWTConfig) grpc.UnaryServerInterceptor
- func LoadPublicKeyFromFile(path string) (*rsa.PublicKey, error)
- func LoadPublicKeyFromPEM(pemBytes []byte) (*rsa.PublicKey, error)
- type AuthContext
- type AuthType
- type JWTConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func APIKeyMiddleware ¶
APIKeyMiddleware returns an HTTP middleware that validates API keys. It checks the Authorization header for "Bearer {key}" format and validates the key against the provided list of valid keys.
On success, it injects an AuthContext into the request context with: - AuthType set to AuthTypeAPIKey - ServiceID set to the API key (for identification in logs)
On failure, it returns 401 Unauthorized.
func APIKeyStreamInterceptor ¶
func APIKeyStreamInterceptor(validKeys []string) grpc.StreamServerInterceptor
APIKeyStreamInterceptor returns a gRPC stream server interceptor that validates API keys. It checks the "authorization" metadata for "Bearer {key}" format and validates the key against the provided list of valid keys.
On success, it injects an AuthContext into the request context. On failure, it returns codes.Unauthenticated status.
func APIKeyUnaryInterceptor ¶
func APIKeyUnaryInterceptor(validKeys []string) grpc.UnaryServerInterceptor
APIKeyUnaryInterceptor returns a gRPC unary server interceptor that validates API keys. It checks the "authorization" metadata for "Bearer {key}" format and validates the key against the provided list of valid keys.
On success, it injects an AuthContext into the request context. On failure, it returns codes.Unauthenticated status.
func JWTMiddleware ¶
JWTMiddleware returns an HTTP middleware that validates JWT tokens. It checks the Authorization header for "Bearer {token}" format and validates: - JWT signature using the provided public key - Expiration time (exp claim) - Issuer (iss claim) if configured - Audience (aud claim) if configured
On success, it injects an AuthContext into the request context with: - AuthType set to AuthTypeJWT - UserID or ServiceID extracted from "sub" claim - Claims populated with all token claims
On failure, it returns 401 Unauthorized.
func JWTStreamInterceptor ¶
func JWTStreamInterceptor(config JWTConfig) grpc.StreamServerInterceptor
JWTStreamInterceptor returns a gRPC stream server interceptor that validates JWT tokens. It checks the "authorization" metadata for "Bearer {token}" format and validates the token using the same rules as JWTMiddleware.
On success, it injects an AuthContext into the request context. On failure, it returns codes.Unauthenticated status.
func JWTUnaryInterceptor ¶
func JWTUnaryInterceptor(config JWTConfig) grpc.UnaryServerInterceptor
JWTUnaryInterceptor returns a gRPC unary server interceptor that validates JWT tokens. It checks the "authorization" metadata for "Bearer {token}" format and validates the token using the same rules as JWTMiddleware.
On success, it injects an AuthContext into the request context. On failure, it returns codes.Unauthenticated status.
func LoadPublicKeyFromFile ¶
LoadPublicKeyFromFile loads an RSA public key from a PEM file. This is a convenience function for loading keys from the filesystem.
Types ¶
type AuthContext ¶
type AuthContext struct {
// UserID is the unique identifier of the authenticated user.
// Empty for service-to-service authentication.
UserID string
// ServiceID is the unique identifier of the authenticated service.
// Empty for user authentication.
ServiceID string
// AuthType indicates the authentication method used (API_KEY or JWT).
AuthType AuthType
// Claims contains additional claims from JWT tokens.
// For API key authentication, this will be nil or empty.
Claims map[string]interface{}
}
AuthContext contains authentication information extracted from a request. It is stored in context.Context and can be retrieved using GetAuthContext.
func GetAuthContext ¶
func GetAuthContext(ctx context.Context) (*AuthContext, error)
GetAuthContext retrieves the AuthContext from the context.Context. Returns an error if no authentication context is found.
func MustGetAuthContext ¶
func MustGetAuthContext(ctx context.Context) *AuthContext
MustGetAuthContext retrieves the AuthContext from the context.Context. Panics if no authentication context is found. Use this only when you are certain that the context has been authenticated by middleware.
func (*AuthContext) GetClaim ¶
func (a *AuthContext) GetClaim(key string) interface{}
GetClaim returns a claim value from the Claims map. Returns nil if the claim doesn't exist.
func (*AuthContext) GetClaimString ¶
func (a *AuthContext) GetClaimString(key string) string
GetClaimString returns a claim value as a string. Returns empty string if the claim doesn't exist or is not a string.
func (*AuthContext) IsService ¶
func (a *AuthContext) IsService() bool
IsService returns true if this is a service authentication context (ServiceID is set).
func (*AuthContext) IsUser ¶
func (a *AuthContext) IsUser() bool
IsUser returns true if this is a user authentication context (UserID is set).
type JWTConfig ¶
type JWTConfig struct {
// PublicKey is the RSA public key used to verify JWT signatures.
PublicKey *rsa.PublicKey
// Issuer is the expected value of the "iss" (issuer) claim.
// If empty, issuer validation is skipped.
Issuer string
// Audience is the expected value of the "aud" (audience) claim.
// If empty, audience validation is skipped.
Audience string
}
JWTConfig contains configuration for JWT validation.