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 ¶
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).
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"
}