csurf
Node.js CSRF protection middleware.
Requires either a session middleware or cookie-parser to be initialized first.
- If you are setting the "cookie" option to a non-
false
value, then you must use cookie-parser before this module. - Otherwise, you must use a session middleware before this module. For example:
If you have questions on how this module is implemented, please read Understanding CSRF.
Installation
This is a Node.js module available through the
npm registry. Installation is done using the
npm install
command:
$ npm install csurf
API
var csurf =
csurf([options])
Create a middleware for CSRF token creation and validation. This middleware
adds a req.csrfToken()
function to make a token which should be added to
requests which mutate state, within a hidden form field, query-string etc.
This token is validated against the visitor's session or csrf cookie.
Options
The csurf
function takes an optional options
object that may contain
any of the following keys:
cookie
Determines if the token secret for the user should be stored in a cookie
or in req.session
. Storing the token secret in a cookie implements
the double submit cookie pattern.
Defaults to false
.
When set to true
(or an object of options for the cookie), then the module
changes behavior and no longer uses req.session
. This means you are no
longer required to use a session middleware. Instead, you do need to use the
cookie-parser middleware in
your app before this middleware.
When set to an object, cookie storage of the secret is enabled and the
object contains options for this functionality (when set to true
, the
defaults for the options are used). The options may contain any of the
following keys:
key
- the name of the cookie to use to store the token secret (defaults to'_csrf'
).path
- the path of the cookie (defaults to'/'
).signed
- indicates if the cookie should be signed (defaults tofalse
).secure
- marks the cookie to be used with HTTPS only (defaults tofalse
).maxAge
- the number of seconds after which the cookie will expire (defaults to session length).httpOnly
- flags the cookie to be accessible only by the web server (defaults tofalse
).sameSite
- sets the same site policy for the cookie(defaults tofalse
). This can be set to'strict'
,'lax'
,'none'
, ortrue
(which maps to'strict'
).domain
- sets the domain the cookie is valid on(defaults to current domain).
ignoreMethods
An array of the methods for which CSRF token checking will disabled.
Defaults to ['GET', 'HEAD', 'OPTIONS']
.
sessionKey
Determines what property ("key") on req
the session object is located.
Defaults to 'session'
(i.e. looks at req.session
). The CSRF secret
from this library is stored and read as req[sessionKey].csrfSecret
.
If the "cookie" option is not false
, then this option does
nothing.
value
Provide a function that the middleware will invoke to read the token from
the request for validation. The function is called as value(req)
and is
expected to return the token as a string.
The default value is a function that reads the token from the following locations, in order:
req.body._csrf
- typically generated by thebody-parser
module.req.query._csrf
- a built-in from Express.js to read from the URL query string.req.headers['csrf-token']
- theCSRF-Token
HTTP request header.req.headers['xsrf-token']
- theXSRF-Token
HTTP request header.req.headers['x-csrf-token']
- theX-CSRF-Token
HTTP request header.req.headers['x-xsrf-token']
- theX-XSRF-Token
HTTP request header.
Example
Simple express example
The following is an example of some server-side code that generates a form that requires a CSRF token to post back.
var cookieParser = var csrf = var bodyParser = var express = // setup route middlewaresvar csrfProtection = var parseForm = bodyParser // create express appvar app = // parse cookies// we need this because "cookie" is true in csrfProtectionapp app app
Inside the view (depending on your template language; handlebars-style
is demonstrated here), set the csrfToken
value as the value of a hidden
input field named _csrf
:
Favorite color: Submit
Using AJAX
When accessing protected routes via ajax both the csrf token will need to be passed in the request. Typically this is done using a request header, as adding a request header can typically be done at a central location easily without payload modification.
The CSRF token is obtained from the req.csrfToken()
call on the server-side.
This token needs to be exposed to the client-side, typically by including it in
the initial page content. One possibility is to store it in an HTML <meta>
tag,
where value can then be retrieved at the time of the request by JavaScript.
The following can be included in your view (handlebar example below), where the
csrfToken
value came from req.csrfToken()
:
The following is an example of using the
Fetch API to post
to the /process
route with the CSRF token from the <meta>
tag on the page:
// Read the CSRF token from the <meta> tagvar token = document // Make a request using the Fetch API
Single Page Application (SPA)
Many SPA frameworks like Angular have CSRF support built in automatically.
Typically they will reflect the value from a specific cookie, like
XSRF-TOKEN
(which is the case for Angular).
To take advantage of this, set the value from req.csrfToken()
in the cookie
used by the SPA framework. This is only necessary to do on the route that
renders the page (where res.render
or res.sendFile
is called in Express,
for example).
The following is an example for Express of a typical SPA response:
appall'*' { rescookie'XSRF-TOKEN' req res}
Ignoring Routes
Note CSRF checks should only be disabled for requests that you expect to come from outside of your website. Do not disable CSRF checks for requests that you expect to only come from your website. An existing session, even if it belongs to an authenticated user, is not enough to protect against CSRF attacks.
The following is an example of how to order your routes so that certain endpoints do not check for a valid CSRF token.
var cookieParser = var csrf = var bodyParser = var express = // create express appvar app = // create api routervar api = // mount api before csrf is appended to the app stackapp // now add csrf and other middlewares, after the "/api" was mountedappappapp app app { var router = router return router}
Custom error handling
When the CSRF token validation fails, an error is thrown that has
err.code === 'EBADCSRFTOKEN'
. This can be used to display custom
error messages.
var bodyParser = var cookieParser = var csrf = var express = var app = appappapp // error handlerapp