csrf

package
v0.82.0 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2026 License: BSD-3-Clause Imports: 12 Imported by: 0

Documentation

Overview

Package csrf provides a robust, stateless, and layered CSRF protection middleware for Go. It implements the Double Submit Cookie pattern using AEAD-encrypted, HostOnly tokens, enhanced with defense-in-depth measures including Origin/Referer validation and session binding. Unlike some CSRF prevention patterns, this middleware works regardless of whether any user session exists, meaning it also protects pre-authentication POST-ish endpoints such as login and registration endpoints. Consumers must ensure that they call either CycleTokenWithProxy or CycleTokenWithWriter (as applicable) whenever sessions are created or destroyed (e.g., on login and logout).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Protector

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

func NewProtector

func NewProtector(cfg ProtectorConfig) *Protector

func (*Protector) CycleTokenWithProxy

func (p *Protector) CycleTokenWithProxy(rp *response.Proxy, sessionID string) error

CycleTokenWithProxy generates a new CSRF token and sets it as a cookie. Must be called on login (with sessionID) and logout (with empty sessionID).

func (*Protector) CycleTokenWithWriter

func (p *Protector) CycleTokenWithWriter(w http.ResponseWriter, r *http.Request, sessionID string) error

CycleTokenWithWriter generates a new CSRF token and sets it as a cookie. Must be called on login (with sessionID) and logout (with empty sessionID).

func (*Protector) Middleware

func (p *Protector) Middleware(next http.Handler) http.Handler

type ProtectorConfig

type ProtectorConfig struct {
	// REQUIRED: A configured cookie manager.
	CookieManager *cookies.Manager
	// REQUIRED: Gets the session ID for the current request. Return empty string if no session exists.
	// This enables automatic session binding validation and smart token cycling.
	GetSessionID   func(r *http.Request) string
	AllowedOrigins []string
	// Defaults to 4 hours, but this is too short for most apps. A good value is to set this to match
	// the TTL of your authentication sessions. It's also a good idea to have your app make any GET
	// request on window focus to refresh the CSRF token, to minimize failure cases for legitimate users.
	TokenTTL time.Duration
	// Do not prefix the name with "__Host-". Prefixing is handled internally.
	// Final cookie name will be "__{Host|Dev}-{CookieName}".
	// Defaults to "csrf_token".
	CookieName string
	HeaderName string // Defaults to "X-CSRF-Token"
}

Jump to

Keyboard shortcuts

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