|
1 | 1 | ### CSRF Protection |
2 | 2 |
|
3 | | -Cross-site request forgery (also known as CSRF or XSRF) is a type of malicious exploit of a website where **unauthorized** commands are transmitted from a user that the web application trusts. To mitigate this kind of attack you can use the [csurf](https://github.com/expressjs/csurf) package. |
| 3 | +Cross-site request forgery (CSRF or XSRF) is a type of attack where **unauthorized** commands are sent from a trusted user to a web application. To help prevent this, you can use the [csrf-csrf](https://github.com/Psifi-Solutions/csrf-csrf) package. |
4 | 4 |
|
5 | 5 | #### Use with Express (default) |
6 | 6 |
|
7 | 7 | Start by installing the required package: |
8 | 8 |
|
9 | 9 | ```bash |
10 | | -$ npm i --save csurf |
| 10 | +$ npm i csrf-csrf |
11 | 11 | ``` |
12 | 12 |
|
13 | | -> warning **Warning** This package is deprecated, refer to [`csurf` docs](https://github.com/expressjs/csurf#csurf) for more information. |
| 13 | +> warning **Warning** As noted in the [csrf-csrf documentation](https://github.com/Psifi-Solutions/csrf-csrf?tab=readme-ov-file#getting-started), this middleware requires session middleware or `cookie-parser` to be initialized beforehand. Please refer to the documentation for further details. |
14 | 14 |
|
15 | | -> warning **Warning** As explained in the [`csurf` docs](https://github.com/expressjs/csurf#csurf), this middleware requires either session middleware or `cookie-parser` to be initialized first. Please see that documentation for further instructions. |
16 | | -
|
17 | | -Once the installation is complete, apply the `csurf` middleware as global middleware. |
| 15 | +Once the installation is complete, register the `csrf-csrf` middleware as global middleware. |
18 | 16 |
|
19 | 17 | ```typescript |
20 | | -import * as csurf from 'csurf'; |
| 18 | +import { doubleCsrf } from 'csrf-csrf'; |
21 | 19 | // ... |
22 | 20 | // somewhere in your initialization file |
23 | | -app.use(csurf()); |
| 21 | +const { |
| 22 | + invalidCsrfTokenError, // This is provided purely for convenience if you plan on creating your own middleware. |
| 23 | + generateToken, // Use this in your routes to generate and provide a CSRF hash, along with a token cookie and token. |
| 24 | + validateRequest, // Also a convenience if you plan on making your own middleware. |
| 25 | + doubleCsrfProtection, // This is the default CSRF protection middleware. |
| 26 | +} = doubleCsrf(doubleCsrfOptions); |
| 27 | +app.use(doubleCsrfProtection); |
24 | 28 | ``` |
25 | 29 |
|
26 | 30 | #### Use with Fastify |
|
0 commit comments