csrf

package
v3.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 17 Imported by: 9

Documentation

Index

Constants

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

HeaderName is the default header name for CSRF tokens.

Variables

View Source
var (
	ErrTokenNotFound    = errors.New("csrf: token not found")
	ErrTokenInvalid     = errors.New("csrf: token invalid")
	ErrFetchSiteInvalid = errors.New("csrf: sec-fetch-site header invalid")
	ErrRefererNotFound  = errors.New("csrf: referer header missing")
	ErrRefererInvalid   = errors.New("csrf: referer header invalid")
	ErrRefererNoMatch   = errors.New("csrf: referer does not match host or trusted origins")
	ErrOriginInvalid    = errors.New("csrf: origin header invalid")
	ErrOriginNoMatch    = errors.New("csrf: origin does not match host or trusted origins")
)
View Source
var ConfigDefault = Config{
	CookieName:            "csrf_",
	CookieSameSite:        "Lax",
	IdleTimeout:           30 * time.Minute,
	KeyGenerator:          utils.SecureToken,
	ErrorHandler:          defaultErrorHandler,
	Extractor:             extractors.FromHeader(HeaderName),
	DisableValueRedaction: false,
}

ConfigDefault is the default config for CSRF middleware.

Functions

func New

func New(config ...Config) fiber.Handler

New creates a new middleware handler

func TokenFromContext

func TokenFromContext(ctx any) string

TokenFromContext returns the token found in the context. It accepts fiber.CustomCtx, fiber.Ctx, *fasthttp.RequestCtx, and context.Context. It returns an empty string if the token does not exist.

Types

type Config

type Config struct {
	// Storage is used to store the state of the middleware.
	//
	// Optional. Default: memory.New()
	// Ignored if Session is set.
	Storage fiber.Storage

	// Next defines a function to skip this middleware when returned true.
	//
	// Optional. Default: nil
	Next func(c fiber.Ctx) bool

	// Session is used to store the state of the middleware.
	//
	// Optional. Default: nil
	// If set, the middleware will use the session store instead of the storage.
	Session *session.Store

	// KeyGenerator creates a new CSRF token.
	//
	// Optional. Default: utils.SecureToken
	KeyGenerator func() string

	// ErrorHandler is executed when an error is returned from fiber.Handler.
	//
	// Optional. Default: defaultErrorHandler
	ErrorHandler fiber.ErrorHandler

	// CookieName is the name of the CSRF cookie.
	//
	// Optional. Default: "csrf_"
	CookieName string

	// CookieDomain is the domain of the CSRF cookie.
	//
	// Optional. Default: ""
	CookieDomain string

	// CookiePath is the path of the CSRF cookie.
	//
	// Optional. Default: ""
	CookiePath string

	// CookieSameSite is the SameSite attribute of the CSRF cookie.
	//
	// Optional. Default: "Lax"
	CookieSameSite string

	// TrustedOrigins is a list of trusted origins for unsafe requests.
	// For requests that use the Origin header, the origin must match the
	// Host header or one of the TrustedOrigins.
	// For secure requests that do not include the Origin header, the Referer
	// header must match the Host header or one of the TrustedOrigins.
	//
	// This supports matching subdomains at any level. This means you can use a value like
	// "https://*.example.com" to allow any subdomain of example.com to submit requests,
	// including multiple subdomain levels such as "https://sub.sub.example.com".
	//
	// Optional. Default: []
	TrustedOrigins []string

	// Extractor returns the CSRF token from the request.
	//
	// Optional. Default: extractors.FromHeader("X-Csrf-Token")
	//
	// Available extractors from github.com/gofiber/fiber/v3/extractors:
	//   - extractors.FromHeader("X-Csrf-Token"): Most secure, recommended for APIs
	//   - extractors.FromForm("_csrf"): Secure, recommended for form submissions
	//   - extractors.FromQuery("csrf_token"): Less secure, URLs may be logged
	//   - extractors.FromParam("csrf"): Less secure, URLs may be logged
	//   - extractors.Chain(...): Advanced chaining of multiple extractors
	//
	// See the Extractors Guide for complete documentation:
	// https://docs.gofiber.io/guide/extractors
	//
	// WARNING: Never create custom extractors that read from cookies with the same
	// CookieName as this defeats CSRF protection entirely.
	Extractor extractors.Extractor

	// IdleTimeout is the duration of time the CSRF token is valid.
	//
	// Optional. Default: 30 * time.Minute
	IdleTimeout time.Duration

	// DisableValueRedaction turns off masking CSRF tokens and storage keys in logs and errors.
	//
	// Optional. Default: false
	DisableValueRedaction bool

	// CookieSecure indicates if CSRF cookie is secure.
	//
	// Optional. Default: false
	CookieSecure bool

	// CookieHTTPOnly indicates if CSRF cookie is HTTP only.
	//
	// Optional. Default: false
	CookieHTTPOnly bool

	// CookieSessionOnly decides whether cookie should last for only the browser session.
	// Ignores Expiration if set to true.
	//
	// Optional. Default: false
	CookieSessionOnly bool

	// SingleUseToken indicates if the CSRF token should be destroyed
	// and a new one generated on each use.
	//
	// Optional. Default: false
	SingleUseToken bool
}

Config defines the config for CSRF middleware.

type Handler

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

Handler for CSRF middleware

func HandlerFromContext

func HandlerFromContext(ctx any) *Handler

HandlerFromContext returns the Handler found in the context. It accepts fiber.CustomCtx, fiber.Ctx, *fasthttp.RequestCtx, and context.Context. It returns nil if the handler does not exist.

func (*Handler) DeleteToken

func (handler *Handler) DeleteToken(c fiber.Ctx) error

DeleteToken removes the token found in the context from the storage and expires the CSRF cookie

type Token

type Token struct {
	Expiration time.Time `json:"expiration"`
	Key        string    `json:"key"`
	Raw        []byte    `json:"raw"`
}

Token represents a CSRF token with expiration metadata. This is used internally for token storage and validation.

Jump to

Keyboard shortcuts

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