newbie. I\'m using ExpressJS/Node. Here\'s my config stuff:
var express = require(\'express\'),
app = express.createServer(),
jade=require(\'jade\');
// Configu
Add the token to dynamic helpers.
app.dynamicHelpers({
token: function(req, res) {
return req.session._csrf;
}
});
Reference it in your jade template.
input(type='hidden', value=token)
Source: http://senchalabs.github.com/connect/middleware-csrf.html
If you also want to set a secure cookie for your CSRF token that can be read by your frontend (angular for example), you can do this:
app.use csrf()
app.use (req, res, next) ->
res.cookie('XSRF-TOKEN', req.csrfToken(), {secure: true})
next()
Dynamic helpers has been removed from Express since 3.x.
The new usage would be app.use(express.csrf());
, which comes from Connect.
In Express 4.x this middleware is removed. For Express 4.x you can do it as follows
var csrf = require('csurf');
app.use(csrf());
Ah!! you need to register the csrf
middleware after your session
and cookieParser
middleware.
Inside Route Or Ctrl
res.render('someform', { csrf: req.csrfToken() });
or You can set a local variable also like so
app.use(function(req, res, next){
res.locals.csrf = req.csrfToken();
});
Then in view
input(type="hidden", name="_csrf", value="#{csrf}")
You are done!! :)