Skip to content

Commit 6b41063

Browse files
committed
update v2 with last changes
1 parent b1c6507 commit 6b41063

File tree

1 file changed

+24
-24
lines changed
  • versioned_docs/version-v2.x/api/middleware

1 file changed

+24
-24
lines changed

versioned_docs/version-v2.x/api/middleware/csrf.md

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@ id: csrf
44

55
# CSRF
66

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 will return a default 403 Forbidden error.
88

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.
1012

1113
## Token Generation
1214

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.
1416

1517
## Security Considerations
1618

@@ -24,34 +26,34 @@ Never use 'safe' methods to mutate data, for example, never use a GET request to
2426

2527
#### Double Submit Cookie Pattern (Default)
2628

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.
2830

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.
3032

3133
:::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>`.
3335
:::
3436

3537
:::note
3638
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.
3739
:::
3840

39-
#### Synchronizer Token Pattern (Session)
41+
#### Synchronizer Token Pattern (with Session)
4042

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.
4244

4345
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.
4446

4547
:::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.
4749
:::
4850

4951
### Defense In Depth
5052

5153
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.
5254

5355
:::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.
5557

5658
To use these prefixes, set the `CookieName` option to `__Host-csrf_` or `__Secure-csrf_`.
5759
:::
@@ -61,7 +63,9 @@ To use these prefixes, set the `CookieName` option to `__Host-csrf_` or `__Secur
6163
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.
6264

6365
:::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.
6569
:::
6670

6771

@@ -74,15 +78,15 @@ Tokens are valid until they expire or until they are deleted. By default, tokens
7478
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.
7579

7680
:::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.
7882
:::
7983

8084
#### Deleting Tokens
8185

8286
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)`.
8387

8488
```go
85-
if handler, ok := app.AcquireCtx(ctx).Locals(ConfigDefault.HandlerContextKey).(*CSRFHandler); ok {
89+
if handler, ok := app.AcquireCtx(ctx).Locals(csrf.ConfigDefault.HandlerContextKey).(*CSRFHandler); ok {
8690
if err := handler.DeleteToken(app.AcquireCtx(ctx)); err != nil {
8791
// handle error
8892
}
@@ -127,20 +131,15 @@ app.Use(csrf.New(csrf.Config{
127131
CookieSameSite: "Lax",
128132
Expiration: 1 * time.Hour,
129133
KeyGenerator: utils.UUIDv4,
130-
Extractor: func(c *fiber.Ctx) (string, error) { ... },
131134
}))
132135
```
133136

134-
:::info
135-
KeyLookup will be ignored if Extractor is explicitly set.
136-
:::
137-
138137
## Config
139138

140139
| Property | Type | Description | Default |
141140
|:------------------|:-----------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------|
142141
| 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" |
144143
| CookieName | `string` | Name of the csrf cookie. This cookie will store the csrf key. | "csrf_" |
145144
| CookieDomain | `string` | Domain of the CSRF cookie. | "" |
146145
| CookiePath | `string` | Path of the CSRF cookie. | "" |
@@ -152,8 +151,8 @@ KeyLookup will be ignored if Extractor is explicitly set.
152151
| SingleUseToken | `bool` | SingleUseToken indicates if the CSRF token be destroyed and a new one generated on each use. (See TokenLifecycle) | false |
153152
| Storage | `fiber.Storage` | Store is used to store the state of the middleware. | `nil` |
154153
| 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. | "" |
157156
| KeyGenerator | `func() string` | KeyGenerator creates a new CSRF token. | utils.UUID |
158157
| CookieExpires | `time.Duration` (Deprecated) | Deprecated: Please use Expiration. | 0 |
159158
| Cookie | `*fiber.Cookie` (Deprecated) | Deprecated: Please use Cookie* related fields. | `nil` |
@@ -180,13 +179,14 @@ var ConfigDefault = Config{
180179

181180
### Recommended Config (with session)
182181

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.
184183

185184
```go
186185
var ConfigDefault = Config{
187186
KeyLookup: "header:" + HeaderName,
188-
CookieName: "csrf_",
187+
CookieName: "__Host-csrf_",
189188
CookieSameSite: "Lax",
189+
CookieSecure: true,
190190
CookieSessionOnly: true,
191191
CookieHTTPOnly: true,
192192
Expiration: 1 * time.Hour,
@@ -218,7 +218,7 @@ The CSRF middleware utilizes a set of sentinel errors to handle various scenario
218218
- `ErrNoReferer`: Indicates that the referer was not supplied.
219219
- `ErrBadReferer`: Indicates that the referer is invalid.
220220

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.
222222

223223
## Custom Error Handler
224224

0 commit comments

Comments
 (0)