middleware/csrf
import "github.com/gofiber/fiber/v3/middleware/csrf"
Constants
HeaderName is the default header name for CSRF tokens.
Source: middleware/csrf/config.go:133
const HeaderName = "X-Csrf-Token"Variables
Source: middleware/csrf/csrf.go:47
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")
)ConfigDefault is the default config for CSRF middleware.
Source: middleware/csrf/config.go:136
var ConfigDefault = Config{
CookieName: "csrf_",
CookieSameSite: "Lax",
IdleTimeout: 30 * time.Minute,
KeyGenerator: utils.SecureToken,
ErrorHandler: defaultErrorHandler,
Extractor: extractors.FromHeader(HeaderName),
DisableValueRedaction: false,
}ErrCrossOriginRequest is the error NewCrossOriginProtection denies a request with.
Source: middleware/csrf/cross_origin.go:15
var ErrCrossOriginRequest = errors.New("csrf: cross-origin request denied")Functions
func HandlerFromContext(ctx any) *Handler
Source: middleware/csrf/csrf.go:265
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 New(config ...Config) fiber.Handler
Source: middleware/csrf/csrf.go:80
New creates a new middleware handler
func NewCrossOriginProtection(config ...CrossOriginConfig) fiber.Handler
Source: middleware/csrf/cross_origin.go:42
NewCrossOriginProtection creates a tokenless CSRF middleware. It rejects unsafe cross-origin browser requests by their Sec-Fetch-Site and Origin headers, like net/http.CrossOriginProtection, and keeps no cookie or state.
func TokenFromContext(ctx any) string
Source: middleware/csrf/csrf.go:254
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
Source: middleware/csrf/config.go:14
Config defines the config for CSRF middleware.
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.
// The store must not have a Codec: the token is kept under a key that is not a
// string, which a store with a Codec does not hold, and New panics for one that has.
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, counted from its
// last use. In session mode behind the session middleware, a token is renewed only
// when less than half of it is left, so there it stays valid for at least half of
// IdleTimeout and at most IdleTimeout after its last use; the cookie expires with
// it. Set twice the idle window you want.
//
// 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
}Fields
Storage fiber.StorageStorage is used to store the state of the middleware.
Optional. Default: memory.New() Ignored if Session is set.
Next func(c fiber.Ctx) boolNext defines a function to skip this middleware when returned true.
Optional. Default: nil
Session *session.StoreSession 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. The store must not have a Codec: the token is kept under a key that is not a string, which a store with a Codec does not hold, and New panics for one that has.
KeyGenerator func() stringKeyGenerator creates a new CSRF token.
Optional. Default: utils.SecureToken
ErrorHandler fiber.ErrorHandlerErrorHandler is executed when an error is returned from fiber.Handler.
Optional. Default: defaultErrorHandler
CookieName stringCookieName is the name of the CSRF cookie.
Optional. Default: "csrf_"
CookieDomain stringCookieDomain is the domain of the CSRF cookie.
Optional. Default: ""
CookiePath stringCookiePath is the path of the CSRF cookie.
Optional. Default: ""
CookieSameSite stringCookieSameSite is the SameSite attribute of the CSRF cookie.
Optional. Default: "Lax"
TrustedOrigins []stringTrustedOrigins 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: []
Extractor extractors.ExtractorExtractor 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.
IdleTimeout time.DurationIdleTimeout is the duration of time the CSRF token is valid, counted from its last use. In session mode behind the session middleware, a token is renewed only when less than half of it is left, so there it stays valid for at least half of IdleTimeout and at most IdleTimeout after its last use; the cookie expires with it. Set twice the idle window you want.
Optional. Default: 30 * time.Minute
DisableValueRedaction boolDisableValueRedaction turns off masking CSRF tokens and storage keys in logs and errors.
Optional. Default: false
CookieSecure boolCookieSecure indicates if CSRF cookie is secure.
Optional. Default: false
CookieHTTPOnly boolCookieHTTPOnly indicates if CSRF cookie is HTTP only.
Optional. Default: false
CookieSessionOnly boolCookieSessionOnly decides whether cookie should last for only the browser session. Ignores Expiration if set to true.
Optional. Default: false
SingleUseToken boolSingleUseToken indicates if the CSRF token should be destroyed and a new one generated on each use.
Optional. Default: false
type CrossOriginConfig
Source: middleware/csrf/cross_origin.go:18
CrossOriginConfig defines the config for NewCrossOriginProtection.
type CrossOriginConfig struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c fiber.Ctx) bool
// ErrorHandler is executed when a request is denied.
//
// Optional. Default: defaultErrorHandler
ErrorHandler fiber.ErrorHandler
// TrustedOrigins is a list of origins allowed to send unsafe cross-origin
// requests. It takes the same values as Config.TrustedOrigins, including
// subdomain wildcards such as "https://*.example.com".
//
// No token backs this check, so a matching origin is trusted completely.
//
// Optional. Default: []
TrustedOrigins []string
}Fields
Next func(c fiber.Ctx) boolNext defines a function to skip this middleware when returned true.
Optional. Default: nil
ErrorHandler fiber.ErrorHandlerErrorHandler is executed when a request is denied.
Optional. Default: defaultErrorHandler
TrustedOrigins []stringTrustedOrigins is a list of origins allowed to send unsafe cross-origin requests. It takes the same values as Config.TrustedOrigins, including subdomain wildcards such as "https://*.example.com".
No token backs this check, so a matching origin is trusted completely.
Optional. Default: []
type Handler
Source: middleware/csrf/csrf.go:63
Handler for CSRF middleware
type Handler struct {
// contains filtered or unexported fields
}func (handler *Handler) DeleteToken(c fiber.Ctx) error
Source: middleware/csrf/csrf.go:334
DeleteToken removes the token found in the context from the storage and expires the CSRF cookie
type Token
Source: middleware/csrf/token.go:9
Token represents a CSRF token with expiration metadata. This is used internally for token storage and validation.
type Token struct {
Expiration time.Time `json:"expiration"`
Key string `json:"key"`
Raw []byte `json:"raw"`
}Fields
Expiration time.Time`json:"expiration"`Key string`json:"key"`Raw []byte`json:"raw"`