auth

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package auth provides authentication middleware for the rig HTTP library.

It supports API Key authentication (via header or query parameter) and Bearer Token authentication. Both middleware types are configurable and store authentication results in the request context for downstream handlers.

Example usage:

r := rig.New()

// Simple API key authentication
api := r.Group("/api")
api.Use(auth.APIKeySimple("my-secret-key"))

// Or with full configuration
api.Use(auth.APIKey(auth.APIKeyConfig{
    Name: "X-API-Key",
    Validator: func(key string) (string, bool) {
        if key == os.Getenv("API_KEY") {
            return "my-service", true
        }
        return "", false
    },
}))

Index

Constants

View Source
const (
	// ContextKeyIdentity holds the authenticated identity (e.g., user ID, service name).
	ContextKeyIdentity = "auth.identity"

	// ContextKeyMethod holds the authentication method used (e.g., "api_key", "bearer").
	ContextKeyMethod = "auth.method"
)

Context keys for accessing authentication information in handlers.

Variables

This section is empty.

Functions

func APIKey

func APIKey(config APIKeyConfig) rig.MiddlewareFunc

APIKey creates middleware that authenticates requests using an API key. The key can be provided via header or query parameter based on configuration.

On successful authentication, the identity is stored in the context and can be retrieved using auth.GetIdentity(c) or c.Get(auth.ContextKeyIdentity).

func APIKeySimple

func APIKeySimple(validKeys ...string) rig.MiddlewareFunc

APIKeySimple creates a simple API Key middleware that validates against a list of keys. It uses constant-time comparison to prevent timing attacks.

This is a convenience function for simple use cases. For more control, use APIKey with a custom Validator.

func Bearer

func Bearer(config BearerConfig) rig.MiddlewareFunc

Bearer creates middleware that authenticates requests using Bearer tokens. It extracts the token from the "Authorization: Bearer <token>" header.

On successful authentication, the identity is stored in the context and can be retrieved using auth.GetIdentity(c) or c.Get(auth.ContextKeyIdentity).

On failure, it sets the WWW-Authenticate header as per RFC 6750.

func GetIdentity

func GetIdentity(c *rig.Context) string

GetIdentity retrieves the authenticated identity from the context. Returns empty string if not authenticated.

func GetMethod

func GetMethod(c *rig.Context) string

GetMethod retrieves the authentication method from the context. Returns empty string if not authenticated. Possible values: "api_key", "bearer".

func IsAuthenticated

func IsAuthenticated(c *rig.Context) bool

IsAuthenticated returns true if the request has been authenticated.

Types

type APIKeyConfig

type APIKeyConfig struct {
	// Source specifies where to look for the API key.
	// Valid values: "header" (default), "query".
	Source string

	// Name is the header name or query parameter key.
	// Default: "X-API-Key".
	Name string

	// Validator is called to validate the API key.
	// It should return the identity (e.g., user ID, service name) and whether the key is valid.
	// The identity is stored in the context under ContextKeyIdentity.
	Validator func(key string) (identity string, valid bool)

	// OnError is called when authentication fails.
	// If nil, a default JSON error response is returned.
	OnError ErrorHandler
}

APIKeyConfig defines the configuration for API Key authentication.

type BearerConfig

type BearerConfig struct {
	// Validator is called to validate the bearer token.
	// It should return the identity (e.g., user ID) and whether the token is valid.
	// The identity is stored in the context under ContextKeyIdentity.
	//
	// The token passed to Validator has already been extracted from the
	// "Authorization: Bearer <token>" header.
	Validator func(token string) (identity string, valid bool)

	// Realm is used in the WWW-Authenticate header on authentication failure.
	// Default: "API".
	Realm string

	// OnError is called when authentication fails.
	// If nil, a default JSON error response is returned with WWW-Authenticate header.
	OnError ErrorHandler
}

BearerConfig defines the configuration for Bearer Token authentication.

type ErrorHandler

type ErrorHandler func(c *rig.Context) error

ErrorHandler is a function that handles authentication errors. It receives the context and should write an appropriate error response.

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
}

ErrorResponse is the default error response structure.

Jump to

Keyboard shortcuts

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