module:middleware/csrf
- Description:
CSRF Protection Middleware
Global mode
Enable via
middleware-csrf-enable = trueto dynamically check every request path, this allows to add more or modify routes to the config without restartingmiddleware-csrf-originand/ormiddleware-csrf-sec-fetch-siteconfig parameters can be configured, only matched paths are checked, so CSRF protection is explicit by the config, no defaults except if matched with any config it checks the presense of both headers Origin: and Sec-Fetch-Site:# Only allow specific origins for /account middleware-csrf-origin-/account/* = http://app.host.com middleware-csrf-origin-/account = https://host.com,http://localhost # Only allow same-site or same-origin Sec-Fetch-Site for /api middleware-csrf-sec-fetch-site-/api/* = same-site middleware-csrf-sec-fetch-site-/api/* = same-origin,same-origin # Only allow same-origin Sec-Fetch-Site middleware-csrf-sec-fetch-site-/* = same-originFixed config mode
To enable just what is in the config on start and ignore new routes, modifying existing routes is still supported
middleware-csrf-enable = fixed
- Source:
Members
(static) args :Array.<ConfigOptions>
- Source:
- Default Value:
[ { "name": "enable", "descr": "Enable the middlware, 'true' means dynamicaly check all requests, 'fixed' means set routes from the config on start" }, { "name": "(origin)-(/.+)", "type": "list", "no_camel": 1, "ephemeral": 1, "onupdate": "", "descr": "Paths to by allowed by origin", "example": "middleware-csrf-origin-/account = http://host.com\nmiddleware-csrf-origin-/account/* = https://host.com,http://localhost" }, { "name": "(sec-fetch-site)-(/.+)", "type": "list", "no_camel": 1, "ephemeral": 1, "onupdate": "", "descr": "Paths to use specific Sec-Fetch-Site header validation by: same-origin, same-site, cross-site, none", "example": "middleware-csrf-sec-fetch-/webhook/* = cross-site\nmiddleware-csrf-sec-fetch-/* = same-origin,same-site" }, { "name": "reset", "type": "callback", "callback": "", "descr": "Reset all rules" }, { "name": "priority", "type": "int", "descr": "Add routes with this priority sorting number, for config mode only" }, { "name": "err-(.+)", "descr": "Error messages for various cases" } ]
Methods
(static) configureMiddleware()
- Description:
Start global middleware if enabled
- Source:
(static) handle(context, next)
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
context |
RequestContext | |
next |
function() |
Example
const { api, middleware } = require("backendjs");
const { csrf } = middleware;
api.app.post("*", csrf)
api.app.post("/account/*", csrf)
api.app.post("/account", { origin: ["host1.com", "host2.com"], secFetchSite: "same-origin", handle: csrf.handle })