Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate CSRF tokens in Express?

newbie. I'm using ExpressJS/Node. Here's my config stuff:

var express = require('express'),
app = express.createServer(),
jade=require('jade');
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.session({ secret: "secretive secret" }));
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(require('stylus').middleware({ src: __dirname + '/public' }));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
app.use(express.csrf());

I found csrf.js in Express directories, and see that it should be generated and assigned to req.body._csrf, but I'm not sure how to access it.

Here's the csrf.js code

module.exports = function csrf(options) {
var options = options || {}
, value = options.value || defaultValue;

return function(req, res, next){
// generate CSRF token
var token = req.session._csrf || (req.session._csrf = utils.uid(24));

// ignore GET (for now)
if ('GET' == req.method) return next();

// determine value
var val = value(req);

// check
if (val != token) return utils.forbidden(res);

next();
}
}; 

Help? Thanks!

like image 286
bear Avatar asked Jan 03 '12 01:01

bear


People also ask

How CSRF tokens are generated?

The CSRF token values contain significant entropy and are unpredictable since the generated tokens use a pseudo-random number generator, a static secret, and a seeded timestamp. In addition to this, tokens are different for each user and are stored only for an active user session.

How use CSRF token in Express JS?

CSRF Token The tokens are present in all forms as hidden fields. So, when the client proceeds to submit the form, it contains a validation voucher that confirms the user intended this action. To implement CSRF tokens in Node. js, we can use the csurf module for creating and validating tokens.

How is CSRF token generated in Rails?

The server generates these tokens, links them to the user session, and stores them in the database. This token is then injected into any form presented to the client as a hidden field. When the client correctly submits the form for validation, it passes the token back to the server.


2 Answers

Dynamic helpers has been removed from Express since 3.x.

The new usage would be app.use(express.csrf());, which comes from Connect.

like image 50
chenglou Avatar answered Sep 22 '22 05:09

chenglou


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

like image 23
fent Avatar answered Sep 23 '22 05:09

fent