3 * Copyright(c) 2011 Sencha Inc.
11 var utils = require('../utils');
16 * CRSF protection middleware.
18 * By default this middleware generates a token named "_csrf"
19 * which should be added to requests which mutate
20 * state, within a hidden form field, query-string etc. This
21 * token is validated against the visitor's `req.session._csrf`
24 * The default `value` function checks `req.body` generated
25 * by the `bodyParser()` middleware, `req.query` generated
26 * by `query()`, and the "X-CSRF-Token" header field.
28 * This middleware requires session support, thus should be added
29 * somewhere _below_ `session()` and `cookieParser()`.
33 * - `value` a function accepting the request, returning the token
35 * @param {Object} options
39 module.exports = function csrf(options) {
40 var options = options || {}
41 , value = options.value || defaultValue;
43 return function(req, res, next){
44 // generate CSRF token
45 var token = req.session._csrf || (req.session._csrf = utils.uid(24));
47 // ignore these methods
48 if ('GET' == req.method || 'HEAD' == req.method || 'OPTIONS' == req.method) return next();
54 if (val != token) return next(utils.error(403));
61 * Default value function, checking the `req.body`
62 * and `req.query` for the CSRF token.
64 * @param {IncomingMessage} req
69 function defaultValue(req) {
70 return (req.body && req.body._csrf)
71 || (req.query && req.query._csrf)
72 || (req.headers['x-csrf-token']);