Documentation
¶
Overview ¶
Package auth provides authentication infrastructure for Credo applications.
Instead of a built-in User field on Context, Credo exposes the authenticated principal through generic *credo.Context methods, and this package provides the Authenticator[T] strategy interface and a middleware factory that populates it. See ADR-012 for the design rationale.
User Accessors ¶
The authenticated user is attached and read through Context methods, with compile-time type safety:
// In middleware (auth.Middleware calls SetUser for you)
c.SetUser(myUser)
// In a Credo handler
user, err := c.RequireUser[*MyUser]()
if err != nil { ... }
Authenticator Interface ¶
Implement Authenticator[T] for your auth strategy (JWT, session, API key):
type MyAuth struct { ... }
func (a *MyAuth) Authenticate(r *http.Request) (*User, error) { ... }
Middleware Factory ¶
Create middleware from any Authenticator:
app.Middleware(auth.Middleware[*User](myAuth, nil)) // every route, mounts included
For custom auth failure handling, provide an ErrorFunc:
auth.Middleware[*User](myAuth, func(err error, c *credo.Context) error {
return c.Response().JSON(401, map[string]string{"error": err.Error()})
})
Built-in Authenticators ¶
This package includes reusable Authenticator implementations:
- NewAPIKeyAuthenticator[T]
- NewBasicAuthenticator[T]
The JWT authenticator is in package auth/jwtauth, so that only an application that verifies JWTs compiles golang-jwt.
Maturity: beta
Index ¶
- Variables
- func BasicChallenge(realm string) string
- func Middleware[T any](a Authenticator[T], onError ErrorFunc) credo.Middleware
- func SecureCompare(x, y string) bool
- type APIKeyAuthenticator
- type APIKeyConfig
- type APIKeyValidator
- type Authenticator
- type BasicAuthenticator
- type BasicConfig
- type BasicValidator
- type ErrorFunc
Constants ¶
This section is empty.
Variables ¶
var ( // ErrAPIKeyMissing is returned when no API key can be extracted. ErrAPIKeyMissing = errors.New("auth: api key is missing") // ErrAPIKeyInvalid is returned when an API key is rejected. ErrAPIKeyInvalid = errors.New("auth: api key is invalid") )
var ( // ErrBasicCredentialsMissing is returned when Basic credentials are absent. ErrBasicCredentialsMissing = errors.New("auth: basic credentials are missing") // ErrBasicCredentialsInvalid is returned when Basic credentials are rejected. ErrBasicCredentialsInvalid = errors.New("auth: basic credentials are invalid") )
Functions ¶
func BasicChallenge ¶
BasicChallenge returns a valid WWW-Authenticate header value for Basic auth.
func Middleware ¶
func Middleware[T any](a Authenticator[T], onError ErrorFunc) credo.Middleware
Middleware creates an credo.Middleware that authenticates requests using the given Authenticator. If authentication succeeds, the user is stored on the request via c.SetUser and is then accessible to downstream handlers via c.GetUser[T]().
When authentication fails and onError is nil (or returns nil), the middleware returns credo.ErrUnauthorized with the authenticator's error as Internal. Provide an ErrorFunc to customize the failure response.
Panics if a is nil: a missing authenticator is a wiring error, so it fails fast at construction instead of rejecting every request at runtime.
func SecureCompare ¶
SecureCompare reports whether x and y are equal, in time independent of their contents. Use it inside BasicValidator and APIKeyValidator implementations when comparing a received credential against a known secret — a plain == comparison returns early on the first differing byte, leaking how much of the secret matched through response timing.
Both inputs are hashed before comparison, so the timing reveals neither the contents nor the lengths of the inputs.
SecureCompare is for comparing against plaintext secrets (API keys, tokens). Stored passwords should instead be verified with a dedicated password hash such as bcrypt or argon2id, whose comparison functions are already timing-safe.
Types ¶
type APIKeyAuthenticator ¶
type APIKeyAuthenticator[T any] struct { // contains filtered or unexported fields }
APIKeyAuthenticator validates API keys extracted from HTTP requests.
func NewAPIKeyAuthenticator ¶
func NewAPIKeyAuthenticator[T any](cfg APIKeyConfig[T]) (*APIKeyAuthenticator[T], error)
NewAPIKeyAuthenticator creates a new API key Authenticator.
func (*APIKeyAuthenticator[T]) Authenticate ¶
func (a *APIKeyAuthenticator[T]) Authenticate(r *http.Request) (T, error)
Authenticate validates request API key credentials.
type APIKeyConfig ¶
type APIKeyConfig[T any] struct { // Header is the header name used for key extraction. // Default: "X-API-Key" when Header and Query are both empty. Header string // Prefix trims an optional scheme prefix from Header value. // Example: "ApiKey" for "Authorization: ApiKey <key>". Prefix string // Query is an optional query parameter fallback. Query string // Validator checks whether the extracted key is valid. Validator APIKeyValidator[T] }
APIKeyConfig defines configuration for APIKeyAuthenticator.
type APIKeyValidator ¶
APIKeyValidator validates an API key and returns an authenticated user. ok=false means credentials were recognized but rejected.
When comparing the key against a known secret, use SecureCompare instead of == to avoid leaking timing information.
type Authenticator ¶
Authenticator validates a request and returns the authenticated user. T is the application's user type (e.g., *MyUser, Claims, etc.).
type BasicAuthenticator ¶
type BasicAuthenticator[T any] struct { // contains filtered or unexported fields }
BasicAuthenticator validates HTTP Basic credentials.
func NewBasicAuthenticator ¶
func NewBasicAuthenticator[T any](cfg BasicConfig[T]) (*BasicAuthenticator[T], error)
NewBasicAuthenticator creates a new Basic Authenticator.
func (*BasicAuthenticator[T]) Authenticate ¶
func (a *BasicAuthenticator[T]) Authenticate(r *http.Request) (T, error)
Authenticate validates request Basic credentials.
func (*BasicAuthenticator[T]) Realm ¶
func (a *BasicAuthenticator[T]) Realm() string
Realm returns the configured Basic auth realm.
type BasicConfig ¶
type BasicConfig[T any] struct { // Validator checks whether username/password are valid. Validator BasicValidator[T] // Realm is used by BasicErrorHandler for WWW-Authenticate. // Default: "Restricted". Realm string }
BasicConfig defines configuration for BasicAuthenticator.
type BasicValidator ¶
type BasicValidator[T any] func(username, password string, r *http.Request) (user T, ok bool, err error)
BasicValidator validates username/password credentials and returns user data. ok=false means credentials were parsed but rejected.
When comparing the password against a known plaintext secret, use SecureCompare instead of == to avoid leaking timing information; stored passwords should be verified with a dedicated password hash (bcrypt, argon2id) instead.
type ErrorFunc ¶
ErrorFunc is called when authentication fails. It receives the error from the Authenticator and should return an appropriate HTTP error (or nil to use the default 401 response).
func BasicErrorHandler ¶
BasicErrorHandler returns an ErrorFunc that adds a Basic challenge header before returning 401 Unauthorized.