CsrfConfig class final
Synchronized-token CSRF protection (double-submit cookie pattern).
A random token is stored in a non-HttpOnly cookie so that same-origin JavaScript can read it and send the same value in a header (typical for SPAs). For HTML forms, use a hidden field matching formFieldName or send the headerName from your front-end.
Multipart requests do not read the body here (the stream would conflict
with HttpRequest.getMultipartData downstream); send the token in
headerName for multipart/form-data.
When ignoreRequestsWithBearer is true (default), requests with an
Authorization: Bearer … header skip the check so stateless APIs using JWT
are not broken. Cookie-based sessions should keep the default for browser
clients and use Bearer only for non-browser API clients.
Add to Pipeline in pipelineBefore:
Pipeline()..add(CsrfConfig().createMiddleware())
Constructors
-
CsrfConfig({String cookieName = 'sparky_csrf', String headerName = 'X-CSRF-Token', String formFieldName = '_csrf', String jsonFieldName = '_csrf', Set<
String> safeMethods = const {'GET', 'HEAD', 'OPTIONS', 'TRACE'}, bool ignoreRequestsWithBearer = true, bool cookieSecure = true, SameSite? cookieSameSite = SameSite.lax, String cookiePath = '/', int? cookieMaxAge, int tokenByteLength = 32}) -
const
Properties
-
Set-CookieMax-Agein seconds, ornullto omit (session cookie).final -
Cookie that stores the CSRF token (readable by same-origin JS).
final
-
Set-CookiePath.final -
Set-CookieSameSiteattribute.final -
Set-CookieattributeSecure(defaulttrue, browsers only send the cookie over HTTPS). Set tofalsefor local HTTP development.final - formFieldName → String
-
For
application/x-www-form-urlencodedbodies.final - hashCode → int
-
The hash code for this object.
no setterinherited
- headerName → String
-
Header the client must send on unsafe methods with the same value as the cookie.
final
- ignoreRequestsWithBearer → bool
-
Skip CSRF validation when
Authorizationstarts withBearer.final - jsonFieldName → String
-
For
application/jsonbodies (top-level key).final - runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
-
safeMethods
→ Set<
String> -
Uppercase method names that do not require a token (RFC 9110 safe semantics).
final
- tokenByteLength → int
-
Number of random bytes used to generate the token (before Base64URL).
final
Methods
-
createMiddleware(
) → MiddlewareNullable - Pipeline middleware: sets the cookie on safe requests; validates on others.
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited