httpauth

package
v2.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 18 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 httpauth adapts an iam.Service to net/http.

It depends only on the iam.Service interface, so it works the same with the in-process service and with a remote one.

Typical use:

auth, _ := httpauth.New(httpauth.Config{Service: svc})
mux.Handle("GET /books", auth.RequirePermission("read", "book", nil)(books))
http.ListenAndServe(addr, auth.Protect(mux))

Protect identifies the caller on every request (session cookie or bearer token), applies cross-origin protection to unsafe methods, and requires a CSRF token for cookie-authenticated unsafe requests. The Require* middlewares then reject anonymous or unauthorized callers.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnauthenticated is passed to the ErrorHandler for anonymous
	// requests to protected handlers.
	ErrUnauthenticated = errors.New("httpauth: authentication required")

	// ErrForbidden is passed to the ErrorHandler for denied requests.
	ErrForbidden = errors.New("httpauth: forbidden")

	// ErrUnavailable is passed to the ErrorHandler, with status 503, when
	// the credential could not be checked because a store failed. It wraps
	// iam.ErrUnavailable. The request is not treated as anonymous: that
	// would make a signed-in user look signed out during an outage.
	ErrUnavailable = fmt.Errorf("httpauth: %w", iam.ErrUnavailable)

	// ErrMFARequired is passed to the ErrorHandler by RequireMFA. It wraps
	// iam.ErrMFARequired.
	ErrMFARequired = fmt.Errorf("httpauth: %w", iam.ErrMFARequired)

	// ErrCSRF is passed to the ErrorHandler when the CSRF token is missing
	// or wrong.
	ErrCSRF = errors.New("httpauth: invalid CSRF token")
)

Functions

func SessionFrom

func SessionFrom(ctx context.Context) (*iam.SessionInfo, bool)

SessionFrom returns the authenticated session, if any.

func SubjectFrom

func SubjectFrom(ctx context.Context) (*iam.Subject, bool)

SubjectFrom returns the authenticated subject, if any.

func WithSubject

func WithSubject(ctx context.Context, subject *iam.Subject, sess *iam.SessionInfo) context.Context

WithSubject returns a context carrying subject and session, as Protect would set them. Intended for tests of handlers.

Types

type CSRFConfig

type CSRFConfig struct {
	// Disabled turns off both checks. Only do this if another layer
	// provides CSRF protection. Bearer-only middlewares don't need it.
	Disabled bool

	// Key derives per-session CSRF tokens (HMAC-SHA256). At least 32
	// bytes. If empty, a random key is generated at startup, so tokens do
	// not survive restarts and differ between instances.
	Key []byte

	// TrustedOrigins are additional origins (scheme://host[:port]) allowed
	// to make cross-origin unsafe requests.
	TrustedOrigins []string

	// HeaderName defaults to "X-CSRF-Token"; FieldName (form field) to
	// "csrf_token".
	HeaderName string
	FieldName  string
}

CSRFConfig configures cross-site request forgery protection.

It only applies when cookie mode is accepted. A bearer-only middleware has no ambient credential for a cross-site request to ride on, so it makes neither check, and cross-origin browser clients (single-page apps, Wasm) work without Disabled or TrustedOrigins; browser access to a bearer API is governed by its CORS policy instead.

type Config

type Config struct {
	Service iam.Service

	// Modes the middleware accepts. Default: cookie only.
	Modes []session.Mode

	Cookie CookieConfig
	CSRF   CSRFConfig

	// TrustedProxies are the networks of reverse proxies whose
	// X-Forwarded-For header is believed. Empty: RemoteAddr is used.
	TrustedProxies []netip.Prefix

	// ErrorHandler writes error responses. Default: JSON {"error": "..."}.
	ErrorHandler func(w http.ResponseWriter, r *http.Request, status int, err error)
}

Config configures the middleware.

type CookieConfig

type CookieConfig struct {
	// Name defaults to "__Host-session", or "session" when Insecure is set
	// (the __Host- prefix requires Secure).
	Name string

	// Insecure drops the Secure attribute. Only for local development over
	// plain HTTP; never in production.
	Insecure bool

	// SameSite defaults to http.SameSiteLaxMode. Strict is also supported;
	// None is rejected.
	SameSite http.SameSite
}

CookieConfig configures the session cookie.

type Middleware

type Middleware struct {
	// contains filtered or unexported fields
}

Middleware is the configured HTTP layer.

func New

func New(cfg Config) (*Middleware, error)

New validates the configuration and returns the middleware.

func (*Middleware) CSRFToken

func (m *Middleware) CSRFToken(r *http.Request) string

CSRFToken returns the CSRF token for the request's cookie session, or "" if the request is not cookie-authenticated. Send it to the page (meta tag, JSON) and echo it back in the X-CSRF-Token header or csrf_token field.

func (*Middleware) ClientInfo

func (m *Middleware) ClientInfo(r *http.Request) iam.ClientInfo

ClientInfo returns the client's IP and user agent for iam requests.

X-Forwarded-For is only used when the direct peer is a trusted proxy; the client IP is then the rightmost address not in TrustedProxies.

func (*Middleware) EndSession

func (m *Middleware) EndSession(w http.ResponseWriter, r *http.Request) error

EndSession logs out the cookie session of r (if any) and clears the cookie.

func (*Middleware) Protect

func (m *Middleware) Protect(next http.Handler) http.Handler

Protect wraps the whole handler tree. It:

  1. when cookie mode is accepted, rejects cross-origin unsafe requests (http.CrossOriginProtection, based on Sec-Fetch-Site / Origin), including unauthenticated ones such as login forms;
  2. identifies the caller from the session cookie or the Authorization header; invalid credentials make the request anonymous, while a store failure while checking them answers 503 with ErrUnavailable;
  3. for unsafe methods authenticated by cookie, requires the per-session CSRF token (header or form field).

Bearer-authenticated requests are not subject to CSRF checks: browsers do not attach Authorization headers automatically.

Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/kararnab/iam/v2"
	"github.com/kararnab/iam/v2/audit"
	"github.com/kararnab/iam/v2/httpauth"
	"github.com/kararnab/iam/v2/memstore"
	"github.com/kararnab/iam/v2/password"
	"github.com/kararnab/iam/v2/policy"
	"github.com/kararnab/iam/v2/provider"
)

func main() {
	ctx := context.Background()
	users := memstore.NewUsers()
	hasher, _ := password.NewArgon2id(password.DefaultParams, 0)
	passwords, _ := password.NewProvider(users, hasher, password.DefaultPolicy)
	rbac, _ := policy.NewRBAC(map[string][]policy.Permission{"member": {policy.P("read", "note")}})
	svc, _ := iam.New(iam.Config{
		Providers: []provider.AuthProvider{passwords},
		Users:     users,
		Sessions:  memstore.NewSessions(),
		Policy:    rbac,
		Audit:     audit.Func(func(context.Context, audit.Event) error { return nil }),
	})

	// Seed one member (normally done by sign-up).
	users.PutSubject(iam.Subject{ID: "ana", Roles: []string{"member"}})
	id, _ := passwords.Register(ctx, map[string]string{"username": "ana@example.com", "password": "correct horse battery staple"})
	_ = users.LinkIdentity(ctx, "ana", *id)

	auth, _ := httpauth.New(httpauth.Config{Service: svc})
	mux := http.NewServeMux()
	mux.Handle("GET /notes", auth.RequirePermission("read", "note", nil)(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			s, _ := httpauth.SubjectFrom(r.Context())
			fmt.Fprint(w, "notes for ", s.ID)
		})))
	handler := auth.Protect(mux)

	// Anonymous request.
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, httptest.NewRequest("GET", "/notes", nil))
	fmt.Println(w.Code)

	// Log in; StartSession sets the __Host-session cookie.
	res, _ := svc.Login(ctx, iam.AuthRequest{Provider: password.ProviderName,
		Params: map[string]string{"username": "ana@example.com", "password": "correct horse battery staple"}})
	login := httptest.NewRecorder()
	auth.StartSession(login, res)
	cookie := login.Result().Cookies()[0]
	fmt.Println(cookie.Name, cookie.HttpOnly, cookie.Secure, cookie.SameSite == http.SameSiteLaxMode)

	r := httptest.NewRequest("GET", "/notes", nil)
	r.AddCookie(cookie)
	w = httptest.NewRecorder()
	handler.ServeHTTP(w, r)
	fmt.Println(w.Code, w.Body.String())
}
Output:
401
__Host-session true true true
200 notes for ana

func (*Middleware) RequireAuth

func (m *Middleware) RequireAuth(next http.Handler) http.Handler

RequireAuth rejects anonymous requests with 401. Use inside Protect.

func (*Middleware) RequireMFA added in v2.2.0

func (m *Middleware) RequireMFA(next http.Handler) http.Handler

RequireMFA rejects anonymous requests (401) and sessions that were not started with a second factor (403, ErrMFARequired). Bearer requests pass only when the service checks sessions on access (iam.Config.VerifySessionOnAccess), since access tokens do not carry the flag.

func (*Middleware) RequirePermission

func (m *Middleware) RequirePermission(action policy.Action, resourceType string, resource func(*http.Request) policy.Resource) func(http.Handler) http.Handler

RequirePermission asks the policy engine whether the caller may perform action on resourceType. resource, if non-nil, fills in the resource ID and attributes from the request (for example r.PathValue("id")).

func (*Middleware) RequireRole

func (m *Middleware) RequireRole(roles ...string) func(http.Handler) http.Handler

RequireRole rejects anonymous requests (401) and subjects without any of the roles (403). Prefer RequirePermission, which goes through the policy engine and is audited.

func (*Middleware) StartSession

func (m *Middleware) StartSession(w http.ResponseWriter, res *iam.LoginResult) string

StartSession sets the session cookie for a cookie-mode login result and returns the CSRF token for the new session. It does nothing for other modes.

Jump to

Keyboard shortcuts

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