You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: versioned_docs/version-v2.x/api/middleware/csrf.md
+24-24Lines changed: 24 additions & 24 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,13 +4,15 @@ id: csrf
4
4
5
5
# CSRF
6
6
7
-
The CSRF middleware for [Fiber](https://github.com/gofiber/fiber) provides protection against [Cross-Site Request Forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery) (CSRF) attacks using tokens. These tokens verify requests made using methods other than those defined as "safe" by [RFC9110#section-9.2.1](https://datatracker.ietf.org/doc/html/rfc9110.html#section-9.2.1) (Safe-Methods: GET, HEAD, OPTIONS, and TRACE). If a potential attack is detected this middleware will, by default, return a 403 Forbidden error.
7
+
The CSRF middleware for [Fiber](https://github.com/gofiber/fiber) provides protection against [Cross-Site Request Forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery) (CSRF) attacks. Requests made using methods other than those defined as 'safe' by [RFC9110#section-9.2.1](https://datatracker.ietf.org/doc/html/rfc9110.html#section-9.2.1) (GET, HEAD, OPTIONS, and TRACE) are validated using tokens. If a potential attack is detected, the middleware willreturn a default 403 Forbidden error.
8
8
9
-
This middleware can be used with or without a user session and offers two token validation patterns. In addition, it implements strict referer checking for HTTPS requests, ensuring the security of your application. For HTTPS requests, even if a subdomain can set or modify cookies on your domain, it can't force a user to post to your application since that request won't come from your own exact domain.
9
+
This middleware offers two [Token Validation Patterns](#token-validation-patterns): the [Double Submit Cookie Pattern (default)](#double-submit-cookie-pattern-default), and the [Synchronizer Token Pattern (with Session)](#synchronizer-token-pattern-session).
10
+
11
+
As a [Defense In Depth](#defense-in-depth) measure, this middleware performs [Referer Checking](#referer-checking) for HTTPS requests.
10
12
11
13
## Token Generation
12
14
13
-
CSRF tokens are generated on 'safe' requests and when the existing token has expired or hasn't been set yet. If `SingleUseToken` is `true`, a new token is generated after each use. Retrieve the CSRF token using `c.Locals(contextKey)`, where `contextKey` is defined in the configuration.
15
+
CSRF tokens are generated on 'safe' requests and when the existing token has expired or hasn't been set yet. If `SingleUseToken` is `true`, a new token is generated after each use. Retrieve the CSRF token using `c.Locals(contextKey)`, where `contextKey` is defined within the configuration.
14
16
15
17
## Security Considerations
16
18
@@ -24,34 +26,34 @@ Never use 'safe' methods to mutate data, for example, never use a GET request to
24
26
25
27
#### Double Submit Cookie Pattern (Default)
26
28
27
-
In the default configuration, the middleware generates and stores tokens using the `fiber.Storage` interface. These tokens are not associated with a user session, and a Double Submit Cookie pattern is used to validate the token. The token is stored in a cookie and sent as a header on requests. The middleware compares the cookie value with the header value to validate the token. This is a secure pattern that does not require a user session.
29
+
By default, the middleware generates and stores tokens using the `fiber.Storage` interface. These tokens are not linked to any particular user session, and they are validated using the Double Submit Cookie pattern. The token is stored in a cookie, and then sent as a header on requests. The middleware compares the cookie value with the header value to validate the token. This is a secure pattern that does not require a user session.
28
30
29
-
When using this pattern, it's important to delete the token when the authorization status changes, see: [Token Lifecycle](#token-lifecycle) for more information.
31
+
When the authorization status changes, the previously issued token MUST be deleted, and a new one generated. See [Token Lifecycle](#token-lifecycle)[Deleting Tokens](#deleting-tokens) for more information.
30
32
31
33
:::caution
32
-
When using this method, it's important to set the `CookieSameSite` option to `Lax` or `Strict` and ensure that the Extractor is not `CsrfFromCookie`, and KeyLookup is not `cookie:<name>`.
34
+
When using this pattern, it's important to set the `CookieSameSite` option to `Lax` or `Strict` and ensure that the Extractor is not `CsrfFromCookie`, and KeyLookup is not `cookie:<name>`.
33
35
:::
34
36
35
37
:::note
36
38
When using this pattern, this middleware uses our [Storage](https://github.com/gofiber/storage) package to support various databases through a single interface. The default configuration for Storage saves data to memory. See [Custom Storage/Database](#custom-storagedatabase) for customizing the storage.
37
39
:::
38
40
39
-
#### Synchronizer Token Pattern (Session)
41
+
#### Synchronizer Token Pattern (with Session)
40
42
41
-
When using this middleware with a user session, the middleware can be configured to store the token in the session. This method is recommended when using a user session, as it is generally more secure than the Double Submit Cookie Pattern.
43
+
When using this middleware with a user session, the middleware can be configured to store the token within the session. This method is recommended when using a user session, as it is generally more secure than the Double Submit Cookie Pattern.
42
44
43
45
When using this pattern it's important to regenerate the session when the authorization status changes, this will also delete the token. See: [Token Lifecycle](#token-lifecycle) for more information.
44
46
45
47
:::caution
46
-
When using this method, pre-sessions are required and will be created if a session is not already present. This means the middleware will create a session for every safe request, even if the request does not require a session. Therefore, the existence of a session should not be used to indicate that a user is logged in or authenticated; a session value should be used for this purpose.
48
+
Pre-sessions are required and will be created automatically if not present. Use a session value to indicate authentication instead of relying on presence of a session.
47
49
:::
48
50
49
51
### Defense In Depth
50
52
51
53
When using this middleware, it's recommended to serve your pages over HTTPS, set the `CookieSecure` option to `true`, and set the `CookieSameSite` option to `Lax` or `Strict`. This ensures that the cookie is only sent over HTTPS and not on requests from external sites.
52
54
53
55
:::note
54
-
Cookie prefixes __Host- and __Secure- can be used to further secure the cookie. However, these prefixes are not supported by all browsers and there are some other limitations. See [MDN#Set-Cookie#cookie_prefixes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes) for more information.
56
+
Cookie prefixes `__Host-` and `__Secure-` can be used to further secure the cookie. Note that these prefixes are not supported by all browsers and there are other limitations. See [MDN#Set-Cookie#cookie_prefixes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes) for more information.
55
57
56
58
To use these prefixes, set the `CookieName` option to `__Host-csrf_` or `__Secure-csrf_`.
57
59
:::
@@ -61,7 +63,9 @@ To use these prefixes, set the `CookieName` option to `__Host-csrf_` or `__Secur
61
63
For HTTPS requests, this middleware performs strict referer checking. Even if a subdomain can set or modify cookies on your domain, it can't force a user to post to your application since that request won't come from your own exact domain.
62
64
63
65
:::caution
64
-
Referer checking is required for https requests protected by CSRF. All modern browsers will automatically include the Referer header in requests, including those made with the JS Fetch API. However, if you are using this middleware with a custom client you must ensure that the client sends a valid Referer header.
66
+
When HTTPS requests are protected by CSRF, referer checking is always carried out.
67
+
68
+
The Referer header is automatically included in requests by all modern browsers, including those made using the JS Fetch API. However, if you're making use of this middleware with a custom client, it's important to ensure that the client sends a valid Referer header.
65
69
:::
66
70
67
71
@@ -74,15 +78,15 @@ Tokens are valid until they expire or until they are deleted. By default, tokens
74
78
By default, tokens may be used multiple times. If you want to delete the token after it has been used, you can set the `SingleUseToken` option to `true`. This will delete the token after it has been used, and a new token will be generated on the next request.
75
79
76
80
:::info
77
-
Using `SingleUseToken` comes with usability trade-offs and is not enabled by default. It can interfere with the user experience if the user has multiple tabs open or uses the back button.
81
+
Using `SingleUseToken` comes with usability trade-offs and is not enabled by default. For example, it can interfere with the user experience if the user has multiple tabs open or uses the back button.
78
82
:::
79
83
80
84
#### Deleting Tokens
81
85
82
86
When the authorization status changes, the CSRF token MUST be deleted, and a new one generated. This can be done by calling `handler.DeleteToken(c)`.
83
87
84
88
```go
85
-
ifhandler, ok:= app.AcquireCtx(ctx).Locals(ConfigDefault.HandlerContextKey).(*CSRFHandler); ok {
89
+
ifhandler, ok:= app.AcquireCtx(ctx).Locals(csrf.ConfigDefault.HandlerContextKey).(*CSRFHandler); ok {
| Next |`func(*fiber.Ctx) bool`| Next defines a function to skip this middleware when returned true. |`nil`|
143
-
| KeyLookup |`string`| KeyLookup is a string in the form of "`<source>:<key>`" that is used to create an Extractor that extracts the token from the request. Possible values: "`header:<name>`", "`query:<name>`", "`param:<name>`", "`form:<name>`", "`cookie:<name>`". Ignored if an Extractor is explicitly set. | "header:X-CSRF-Token" |
142
+
| KeyLookup |`string`| KeyLookup is a string in the form of "`<source>:<key>`" that is used to create an Extractor that extracts the token from the request. Possible values: "`header:<name>`", "`query:<name>`", "`param:<name>`", "`form:<name>`", "`cookie:<name>`". Ignored if an Extractor is explicitly set. | "header:X-Csrf-Token" |
144
143
| CookieName |`string`| Name of the csrf cookie. This cookie will store the csrf key. | "csrf_" |
145
144
| CookieDomain |`string`| Domain of the CSRF cookie. | "" |
146
145
| CookiePath |`string`| Path of the CSRF cookie. | "" |
@@ -152,8 +151,8 @@ KeyLookup will be ignored if Extractor is explicitly set.
152
151
| SingleUseToken |`bool`| SingleUseToken indicates if the CSRF token be destroyed and a new one generated on each use. (See TokenLifecycle) | false |
153
152
| Storage |`fiber.Storage`| Store is used to store the state of the middleware. |`nil`|
154
153
| Session |`*session.Store`| Session is used to store the state of the middleware. Overrides Storage if set. |`nil`|
155
-
| SessionKey |`string`| SessionKey is the key used to store the token in the session. | "fiber.csrf.token" |
156
-
| ContextKey |`string`| Context key to store the generated CSRF token into the context. If left empty, the token will not be stored in the context. | "" |
154
+
| SessionKey |`string`| SessionKey is the key used to store the token within the session. | "fiber.csrf.token" |
155
+
| ContextKey |`string`| Context key to store the generated CSRF token into the context. If left empty, the token will not be stored within the context. | "" |
157
156
| KeyGenerator |`func() string`| KeyGenerator creates a new CSRF token. | utils.UUID |
| Cookie |`*fiber.Cookie` (Deprecated) | Deprecated: Please use Cookie* related fields. |`nil`|
@@ -180,13 +179,14 @@ var ConfigDefault = Config{
180
179
181
180
### Recommended Config (with session)
182
181
183
-
It's recommended to use this middleware with [fiber/middleware/session](https://docs.gofiber.io/api/middleware/session) to store the CSRF token in the session. This is generally more secure than the default configuration.
182
+
It's recommended to use this middleware with [fiber/middleware/session](https://docs.gofiber.io/api/middleware/session) to store the CSRF token within the session. This is generally more secure than the default configuration.
184
183
185
184
```go
186
185
varConfigDefault = Config{
187
186
KeyLookup: "header:" + HeaderName,
188
-
CookieName: "csrf_",
187
+
CookieName: "__Host-csrf_",
189
188
CookieSameSite: "Lax",
189
+
CookieSecure: true,
190
190
CookieSessionOnly: true,
191
191
CookieHTTPOnly: true,
192
192
Expiration: 1 * time.Hour,
@@ -218,7 +218,7 @@ The CSRF middleware utilizes a set of sentinel errors to handle various scenario
218
218
-`ErrNoReferer`: Indicates that the referer was not supplied.
219
219
-`ErrBadReferer`: Indicates that the referer is invalid.
220
220
221
-
If you are using the default error handler, it will return a 403 Forbidden error for any of these errors without providing any additional information to the client.
221
+
If you use the default error handler, the client will receive a 403 Forbidden error without any additional information.
0 commit comments