一个实用程序包,可帮助使用 express 中的双提交 Cookie 规范实现无状态 CSRF 防护。
Double CSRF
A utility package to help implement stateless CSRF (Cross-Site Request Forgery) protection using the signed Double Submit Cookie Pattern in express.
Getting Started • Configuration • Utilities • FAQ • Support
Background
This module provides the necessary pieces required to implement CSRF protection using the signed Double Submit Cookie Pattern. This is a stateless CSRF protection pattern, if you are using sessions it is highly recommended that you use csrf-sync for the Synchroniser Token Pattern instead.
Since csurf has been deprecated I struggled to find alternative solutions that were accurately implemented and configurable, so I decided to write my own! Thanks to NextAuth as I referenced their implementation. From experience CSRF protection libraries tend to complicate their configuration, and if misconfigured, can render the protection completely useless.
This is why csrf-csrf aims to provide a simple and targeted implementation to simplify its use.
Getting Started
Version 4 is now live! If you are upgrading from version 3 check the changelog, the upgrade guide, and the updated configuration documentation below.
Before getting started with csrf-csrf you should consult the FAQ and determine whether you need CSRF protection and whether csrf-csrf is the right choice.
This section will guide you through using the default setup, which sufficiently implements the signed Double Submit Cookie Pattern. If you would like to customise the configuration, see the configuration section.
You will need to have the cookie-parser middleware registered before the doubleCsrfProtection middleware. If you are using express-session then it is also best to register the cookie-parser middleware after that.
This utility will set a cookie containing a hmac based CSRF token, the frontend should include this CSRF token in an appropriate request header or in the body. The getTokenFromRequest option should strictly return the CSRF token from either a request header, or the request body. If you have cases where you need to consider both make these as explicit as possible to avoid the same vulnerability as csurf, do not just use fallthroughs (||, ??).
If you are using TypeScript, requires TypeScript >= 3.8
npm install cookie-parser csrf-csrf// ESM
import { doubleCsrf } from "csrf-csrf";
// CommonJS
const { doubleCsrf } = require("csrf-csrf");const {
invalidCsrfTokenError, // This is just for convenience if you plan on making your own middleware.
generateCsrfToken, // Use this in your routes to provide a CSRF token.
validateRequest, // Also a convenience if you plan on making your own middleware.
doubleCsrfProtection, // This is the default CSRF protection middleware.
} = doubleCsrf({
getSecret: (req) => 'return some cryptographically pseudorandom secret here',
getSessionIdentifier: (req) => req.session.id // return the requests unique identifier
});This will extract the default utilities, you can configure these and re-export them from your own module. Primarily csrf-csrf was built to support Single Page Applications (SPAs), or frontends hosted cross-site to their backend, the default configuration is optimised for this usecase. If you are changing any of the configuration you should ensure you understand the impact of the change. Consult the documentation for the respective configuration option and also consider reading the FAQ.
To create a route which generates a CSRF token and a cookie containing the CSRF token:
const myRoute = (req, res) => {
const csrfToken = generateCsrfToken(req, res);
// You could also pass the token into the context of a HTML response.
res.json({ csrfToken });
};
const myProtectedRoute = (req, res) =>
res.json({ unpopularOpinion: "Game of Thrones was amazing" });Instead of importing and using generateCsrfToken, you can also use req.csrfToken any time after the doubleCsrfProtection middleware has executed on a request.
request.csrfToken(); // same as generateCsrfToken(req, res);You can also put the token into the context of a templated HTML response.
// Make sure your session middleware is registered before these
express.use(session);
express.use(cookieParser);
express.get("/csrf-token", myRoute);
express.use(doubleCsrfProtection);
// Any non GET routes registered after this will be considered "protected"By default, any requests that are not GET, HEAD, or OPTIONS methods will be protected. You can configure this with the ignoredMethods option. Keep in mind that only requests with side effects need to be protected, it is generally bad practice to have side effects from GET requests.
You can also protect routes on a case-to-case basis:
app.get("/secret-stuff", doubleCsrfProtection, myProtectedRoute); Once a route is protected, you will need to ensure the CSRF token cookie is sent along with the request and by default you will need to include the CSRF token in the x-csrf-token header, otherwise you will receive a 403 - ForbiddenError: invalid csrf token. If your cookie is not being included in your requests be sure to check your withCredentials, CORs configuration, and ensure appropriate sameSite configuration for your use case. For additional information on figuring out the error see the "Dealing with 'ForbiddenError: invalid csrf token'" section of the FAQ.
Sessions
Once again, if you are using sessions, you should be using csrf-sync instead. Sessions have server side state by default.
If you do plan on using express-session with csrf-csrf then ensure your cookie-parser middleware is registered after express-session, as express-session parses its own cookies and may conflict.
Using asynchronously
csrf-csrf itself will not support promises or async, however there is a way around this. If your CSRF token is stored externally and needs to be retrieved asynchronously, you can register an asynchronous middleware first, which exposes the token.
(req, res, next) => {
getCsrfTokenAsync(req)
.then((token) => {
req.asyncCsrfToken = token;
next();
})
.catch((error) => next(error));
};And in this example, your getCsrfTokenFromRequest would look like this:
(req) => req.asyncCsrfToken;Configuration
When initialising doubleCsrf, you have a lot of options available for configuration, the only required options are getSecret and getSessionIdentifier, the rest have sensible defaults (shown below).
…getSecret
(request?: Request) => string | string[]Required
This should return a secret key or an array of secret keys to be used for hmac generation. Secret keys should be cryptographically pseudorandomly generated. You should make sure you use a strong and secure secret key. See the "How to secret?" section of the FAQ.
In case multiple are provided, the first one will be used for hashing. For validation, all secrets will be tried, preferring the first one in the array. Having multiple valid secrets can be useful when you need to rotate secrets, but you do not want to invalidate the previous secret (which might still be used by some users) right away.
getSessionIdentifier
(request: Request) => string;Required
This function should return the unique identifier for the incoming request, typically this would be the session id or JWT. The unique identifier should be something that is different each time it is constructed for the same user. The return value is used as part of the message to generate the hmac, it ensures that generated CSRF tokens can only work for the matching identifier that originally requested them.
If you are rotating your sessions (which you should be), you will need to ensure a new CSRF token is generated at the same time. This should typically be done when a session has some sort of authorisation elevation (e.g. signed in, signed out, sudo). If you're using a JWT and you aren't using it as a cookie, you likely don't need CSRF protection, check the Do I need CSRF protection?" section of the FAQ.
cookieName
string;Optional
Default: "__Host-psifi.x-csrf-token"
The name of the cookie that will be used to track the CSRF token. If you change this it is recommend that you continue to use the __Host- or __Secure- security prefix for production.
Change for development
The security prefix requires the secure flag to be true and requires requests to be received via HTTPS, unless you have your local instance running via HTTPS, you will need to change this value in your development environment.
cookieOptions
{
sameSite?: string;
path?: string;
secure?: boolean
...remainingCookieOptions // See below.
}Optional
Default:
{
sameSite: "strict",
path: "/",
secure: true,
httpOnly: true
}The options provided to the cookie, see cookie attributes. If you plan on changing the httpOnly to false, see the "Does httpOnly have to be true" section of the FAQ. The remaining options are all undefined by default and consist of:
maxAge?: number | undefined;
expires?: Date | undefined;
domain?: string | undefined;
encode?: (val: string) => stringNote that the signed cookie option is not available, it is redundant here. The CSRF tokens generated by csrf-csrf are already signed
messageDelimiter
string;Optional
Default: "!"
The messageDelimiter is used when concatenating the message that will be used for hmac generation. This should be different to the csrfTokenDelimiter
csrfTokenDelimiter
string;Optional
Default: "."
The csrfTokenDelimiter is used to concatenate the hmac and the random value to construct the CSRF token. The random value portion is used to reconstruct the hmac during validation and helps prevent collisions.
getCsrfTokenFromRequest
(req: Request) => string | null | undefined;Optional
Default:
(req: Request) => req.headers["x-csrf-token"];This function should return the token sent by the frontend, either in the request body/payload, or from the x-csrf-token header. Do NOT return the value from the cookie in this function, this would be the same as having no csrf protection at all, see the "Why is using the cookie in getTokenFromRequest a bad idea?" section of the FAQ.
hmacAlgorithm
string;Optional
Default: "sha256"
The algorithm passed to the createHmac call when generating a token.
ignoredMethods
Array;Optional
Default: ["GET", "HEAD", "OPTIONS"]
An array of request methods that the doubleCsrfProtection middleware will ignore, requests made matching these request methods will not be protected. It is recommended you leave this as the default. If you have GET requests with side effects and need those protected, consider route based protection and/or making use of skipCsrfProtection by skipping for all GET requests except for those that need it.
size
number;Optional
Default: 32
The size in bytes of the random value that will be generated and used for hmac generation.
errorConfig
statusCode?: number;
message?: string;
code?: string | undefined;Optional
Default:
{
statusCode: 403,
message: "invalid csrf token",
code: "EBADCSRFTOKEN"
}Used to customise the error response statusCode, the contained error message, and its code, the error is constructed via createHttpError. The default values match that of csurf for convenience.
skipCsrfProtection
(req: Request) => boolean;Optional - Use this option with extreme caution*
Used to determine whether CSRF protection should be skipped for the given request. If this callback is provided and the request is not in the ignoredMethods, then the callback will be called to determine whether or not CSRF token validation should be checked. If it returns true the CSRF protection will be skipped, if it
暂无开放 Issues,或尚未同步最近议题。