Documentation
¶
Index ¶
- Constants
- func CSRFTemplateField(r *http.Request) template.HTML
- func CSRFToken(r *http.Request) string
- func CapRequestBody(w http.ResponseWriter, r *http.Request)
- func DenyFraming(w http.ResponseWriter)
- func IsBodyTooLargeError(err error) bool
- func LimitBody(maxBytes int64) func(http.Handler) http.Handler
- func LimitBodyReader(w http.ResponseWriter, r *http.Request, maxBytes int64)
- func LocalRedirect(target, fallback string) string
- func SecurityHeaders() func(http.Handler) http.Handler
- func SecurityHeadersWithConfig(cfg SecurityHeadersConfig) func(http.Handler) http.Handler
- type CSRFMiddleware
- type Middleware
- type OneAuth
- type SecurityHeadersConfig
Constants ¶
const DefaultMaxBodySize = 1 << 20 // 1MB
DefaultMaxBodySize is the default request body size limit (1MB).
const MaxFormBodySize = 64 << 10
MaxFormBodySize bounds the body of an auth endpoint: a token, revocation, introspection, PAR or device request, or a login, signup or reset form. Real ones are a few kilobytes; without a bound, Go reads up to 10 MB of form and any amount of JSON (CWE-770).
Variables ¶
This section is empty.
Functions ¶
func CSRFTemplateField ¶
CSRFTemplateField returns an HTML hidden input field containing the CSRF token. Use this in templates: {{.CSRFField}}
func CSRFToken ¶
CSRFToken extracts the CSRF token from the request context. Returns an empty string if the CSRF middleware is not active.
func CapRequestBody ¶ added in v0.1.48
func CapRequestBody(w http.ResponseWriter, r *http.Request)
CapRequestBody limits r.Body to MaxFormBodySize, so ParseForm or a JSON decode past it fails and the handler answers with its usual 400. Call it before the first read. w may be nil (in a helper that only has the request); with a writer, the server also closes the connection once the limit is hit.
func DenyFraming ¶ added in v0.1.45
func DenyFraming(w http.ResponseWriter)
DenyFraming stops a browser from rendering the response inside another site's frame, which is how a clickjacking page tricks a signed-in user into clicking "Approve" (RFC 6749 §10.13, CWE-1021). It always sets X-Frame-Options: DENY, and adds a Content-Security-Policy of frame-ancestors 'none' only when the response has no policy yet, so a deployment's own CSP (from SecurityHeaders or its middleware) is kept.
Call it before writing the body of any page that asks the user to act: consent, login, password and device-code forms.
func IsBodyTooLargeError ¶ added in v0.0.42
IsBodyTooLargeError checks if an error is from http.MaxBytesReader exceeding its limit.
func LimitBody ¶ added in v0.0.42
LimitBody returns middleware that limits the request body to maxBytes. If the body exceeds the limit, a 413 Request Entity Too Large response is sent before the handler runs. This prevents memory exhaustion from oversized JSON bodies (CWE-400: Uncontrolled Resource Consumption).
Usage:
mux.Handle("/api/login", httpauth.LimitBody(1<<20)(loginHandler))
Or wrap an entire mux:
http.ListenAndServe(":8080", httpauth.LimitBody(1<<20)(mux))
func LimitBodyReader ¶ added in v0.0.42
func LimitBodyReader(w http.ResponseWriter, r *http.Request, maxBytes int64)
LimitBodyReader is a lower-level helper that wraps a request body with http.MaxBytesReader. Unlike LimitBody middleware, it doesn't reject upfront — the error occurs when the handler tries to read past the limit. Use this when you need to apply limits inside a handler rather than as middleware.
func LocalRedirect ¶ added in v0.1.45
LocalRedirect returns target when it is a path on this site, and fallback otherwise. Use it for any redirect whose destination came from the request (a ?to= or ?next= parameter, a callback cookie), or the endpoint becomes an open redirect (CWE-601).
A local path starts with a single "/" and has no scheme or host: "/dashboard?tab=x" is local, while "https://evil.example", "//evil.example" and "/\evil.example" (which browsers treat as protocol-relative) are not.
func SecurityHeaders ¶ added in v0.0.43
SecurityHeaders returns middleware that sets standard security headers on every response. These headers protect against common web vulnerabilities:
- HSTS: forces HTTPS connections (RFC 6797)
- X-Content-Type-Options: prevents MIME sniffing
- X-Frame-Options: prevents clickjacking
- Content-Security-Policy: mitigates XSS
- Referrer-Policy: controls referrer leakage
- Permissions-Policy: disables unnecessary browser APIs
Usage:
mux := http.NewServeMux()
handler := httpauth.SecurityHeaders()(mux)
http.ListenAndServe(":8080", handler)
func SecurityHeadersWithConfig ¶ added in v0.0.43
func SecurityHeadersWithConfig(cfg SecurityHeadersConfig) func(http.Handler) http.Handler
SecurityHeadersWithConfig returns middleware using the provided configuration.
Types ¶
type CSRFMiddleware ¶
type CSRFMiddleware struct {
// CookieName is the name of the CSRF cookie. Default: "csrf_token".
CookieName string
// FieldName is the form field name to check. Default: "csrf_token".
FieldName string
// HeaderName is the HTTP header to check. Default: "X-CSRF-Token".
HeaderName string
// MaxAge is the cookie lifetime in seconds. Default: 3600 (1 hour).
MaxAge int
// Secure sets the Secure flag on the cookie (for HTTPS).
Secure bool
// SameSite sets the SameSite attribute. Default: SameSiteStrictMode.
SameSite http.SameSite
// Path sets the cookie path. Default: "/".
Path string
// ErrorHandler is called when CSRF validation fails. Default: 403 JSON response.
ErrorHandler http.HandlerFunc
// ExemptFunc returns true if the request should skip CSRF validation.
// Default: exempt requests with an Authorization: Bearer header.
ExemptFunc func(*http.Request) bool
}
CSRFMiddleware implements the double-submit cookie pattern for CSRF protection. It generates a random token stored in a cookie and validates that state-changing requests include a matching token in a form field or header.
Bearer-token requests are exempt by default since they are not vulnerable to CSRF. The cookie is NOT HttpOnly so JavaScript can read it for AJAX header submission.
func (*CSRFMiddleware) Protect ¶
func (m *CSRFMiddleware) Protect(next http.Handler) http.Handler
Protect returns middleware that enforces CSRF protection. Safe methods (GET, HEAD, OPTIONS) receive a CSRF cookie and have the token injected into the request context. Unsafe methods must include a matching token in either the form field or header.
type Middleware ¶
type Middleware struct {
AuthTokenHeaderName string
AuthTokenCookieName string
SubjectParamName string
CallbackURLParam string
SessionGetter func(r *http.Request, param string) any
GetRedirURL func(r *http.Request) string
DefaultRedirectURL string
VerifyToken func(tokenString string) (loggedInSubject string, token any, err error)
}
func (*Middleware) EnsureReasonableDefaults ¶
func (a *Middleware) EnsureReasonableDefaults()
*
- Ensures that config values have reasonable defaults.
func (*Middleware) EnsureUser ¶
func (a *Middleware) EnsureUser(next http.Handler) http.Handler
func (*Middleware) ExtractUser ¶
func (a *Middleware) ExtractUser(next http.Handler) http.Handler
*
- Fetches the subject from the request and loads it into the request
- context for downstream handlers. *
- Note this does not perform any redirects if a valid subject does not
- exist. To also enforce that, use EnsureUser.
func (*Middleware) GetLoggedInSubject ¶ added in v0.1.4
func (a *Middleware) GetLoggedInSubject(r *http.Request) string
GetLoggedInSubject returns the authenticated subject (RFC 7519 `sub`) for the current request — a user ID for human-driven flows or a client_id for client_credentials.
type OneAuth ¶
type OneAuth struct {
Session *scs.SessionManager
Middleware Middleware
// Optional name that can be used as a prefix for all required vars
AppName string
// Name of the session variable where the auth token is stored
AuthTokenSessionVar string
// All the domains where the auth token cookies will be set on a login success or logout
CookieDomains []string
// JWT related fields
JwtIssuer string
JWTSecretKey string
// How long is a session cookie valid for. Defaults to 1 day
SessionTimeoutInSeconds int
// InsecureCookies drops the Secure attribute from the login cookies.
// They are Secure by default, which browsers honour over https and on
// http://localhost; set this only for plain-http development on any
// other host. Every other attribute (HttpOnly on the token, SameSite)
// is kept either way.
InsecureCookies bool
// contains filtered or unexported fields
}
OneAuth owns the session/JWT/mux transport machinery shared across auth flows. Provider-mediated (OAuth/SAML) callback orchestration lives in federatedauth/; username/password handlers live in localauth/.
func (*OneAuth) EnsureDefaults ¶
func (*OneAuth) SetLoggedInSubject ¶ added in v0.1.4
SetLoggedInSubject stores the authenticated subject (RFC 7519 `sub` — a user ID for human-driven flows or a client_id for client_credentials) on each configured cookie domain. Pass an empty string to clear (logout).
Callers (typically federatedauth or localauth) translate their User object to user.Id() at the call site.
type SecurityHeadersConfig ¶ added in v0.0.43
type SecurityHeadersConfig struct {
// HSTS max-age in seconds. Set to 0 to disable. Default: 31536000 (1 year).
HSTSMaxAge int
// Include subdomains in HSTS. Default: true.
HSTSIncludeSubDomains bool
// X-Frame-Options value. Default: "DENY". Set to "" to disable.
FrameOptions string
// Content-Security-Policy value. Default: "default-src 'self'". Set to "" to disable.
ContentSecurityPolicy string
// Referrer-Policy value. Default: "strict-origin-when-cross-origin". Set to "" to disable.
ReferrerPolicy string
// Permissions-Policy value. Default: disables camera, mic, geo. Set to "" to disable.
PermissionsPolicy string
// Cross-Origin-Embedder-Policy value. Default: "credentialless". Set to "" to disable.
CrossOriginEmbedderPolicy string
// Cross-Origin-Opener-Policy value. Default: "same-origin". Set to "" to disable.
CrossOriginOpenerPolicy string
// Cross-Origin-Resource-Policy value. Default: "same-origin". Set to "" to disable.
CrossOriginResourcePolicy string
}
SecurityHeadersConfig controls which security headers are set.
func DefaultSecurityHeadersConfig ¶ added in v0.0.43
func DefaultSecurityHeadersConfig() SecurityHeadersConfig
DefaultSecurityHeadersConfig returns secure defaults.