auth

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Constants

This section is empty.

Variables

View Source
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")
)
View Source
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

func BasicChallenge(realm string) string

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

func SecureCompare(x, y string) bool

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

type APIKeyValidator[T any] func(key string, r *http.Request) (user T, ok bool, err error)

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

type Authenticator[T any] interface {
	Authenticate(r *http.Request) (T, error)
}

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

type ErrorFunc func(err error, ctx *credo.Context) error

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

func BasicErrorHandler(realm string) ErrorFunc

BasicErrorHandler returns an ErrorFunc that adds a Basic challenge header before returning 401 Unauthorized.

Directories

Path Synopsis
Package jwtauth provides a JWT authenticator for Credo applications.
Package jwtauth provides a JWT authenticator for Credo applications.

Jump to

Keyboard shortcuts

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