Help us shape the future of Go! Take the 2026 Go Developer Survey

csrf

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package csrf protects state-changing requests from cross-site request forgery using Go's http.CrossOriginProtection (Fetch Metadata and Origin checks, no tokens needed in modern browsers), with an optional session-token fallback for clients that send neither header.

Index

Constants

View Source
const FieldName = "_token"

FieldName is the form field carrying the fallback token.

View Source
const HeaderName = "X-CSRF-Token"

HeaderName is the request header carrying the fallback token.

Variables

This section is empty.

Functions

func Middleware

func Middleware(cfg Config) (func(http.Handler) http.Handler, error)

Middleware returns CSRF middleware for the router stack (after session middleware when TokenFallback is enabled). Rejections answer 403 through the error handler and log a "csrf.rejected" security event (A01/A08).

func Token

func Token(ctx context.Context) string

Token returns the session's CSRF token, creating it on first use. Templates expose it as {{ csrfToken }} / {{ csrfField }}; htmx sends it with hx-headers:inherited. It returns "" without a session.

Types

type Config

type Config struct {
	// TrustedOrigins are other origins allowed to send unsafe requests,
	// e.g. "https://admin.example.com".
	TrustedOrigins []string
	// BypassPatterns are ServeMux patterns exempt from checks (webhooks).
	// Bypasses are explicit and logged at boot by the caller.
	BypassPatterns []string
	// TokenFallback requires a session token on unsafe requests that carry
	// neither Sec-Fetch-Site nor Origin but do carry a session (old
	// browsers). API clients without sessions are unaffected.
	TokenFallback bool
}

Config configures Middleware.

Jump to

Keyboard shortcuts

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