middleware/csrf

module:middleware/csrf

Description:
  • CSRF Protection Middleware

    Global mode

    Enable via middleware-csrf-enable = true to dynamically check every request path, this allows to add more routes to the config without restarting

    middleware-csrf-origin and/or middleware-csrf-sec-fetch-site config 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-origin
    

    Fixed config mode

    To enable just what is in the config on start and ignore subsequent config changes

    middleware-csrf-enable = fixed
    
Source:

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 })