auth

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2025 License: MIT Imports: 13 Imported by: 0

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIKeyMiddleware

func APIKeyMiddleware(validKeys []string) func(http.Handler) http.Handler

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

func JWTMiddleware(config JWTConfig) func(http.Handler) http.Handler

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

func LoadPublicKeyFromFile(path string) (*rsa.PublicKey, error)

LoadPublicKeyFromFile loads an RSA public key from a PEM file. This is a convenience function for loading keys from the filesystem.

func LoadPublicKeyFromPEM

func LoadPublicKeyFromPEM(pemBytes []byte) (*rsa.PublicKey, error)

LoadPublicKeyFromPEM loads an RSA public key from PEM-encoded bytes. This is a helper function for loading public keys from configuration.

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 AuthType

type AuthType string

AuthType represents the type of authentication used.

const (
	// AuthTypeAPIKey represents API key authentication.
	AuthTypeAPIKey AuthType = "API_KEY"

	// AuthTypeJWT represents JWT token authentication.
	AuthTypeJWT AuthType = "JWT"
)

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.

Jump to

Keyboard shortcuts

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