I'm very new to express and nodejs in general. I wonder how can I enable csrf protection? Problem is that there are so many different tutorials for different versions and it's totally not backwards-compatable.
I've tried couple of approaches and they don't seem to work, this is what I have now. Problem is that in my form the csrf value is empty.
app.js
var express = require('express');
var http = require('http');
var path = require('path');
var validator = require('express-validator');
var app = express();
app.configure(function() {
app.set('port', 3001);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('secret'));
app.use(express.bodyParser());
app.use(validator());
app.use(express.session());
app.use(express.csrf()); // Okey, I've used this middleware
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.errorHandler());
});
app.get('/', function(req, res) {
res.render('admin/login');
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
admin/login.jade
doctype 5
html
head
title= title
body
form(method='post', action='/admin')
input(type='hidden', name='csrf', value=token)
input(type='text', name='username')
input(type='password', name='password')
input(type='submit', value='Login')
Yo need to store the generated token in the res.locals object to make it available from the template, for example using another middleware, in this example it's passed to the template in every request:
app.use(express.csrf());
app.use(function (req, res, next) {
res.locals.csrftoken = req.csrfToken();
next();
});
And then in your template
div
form(method="post",action="/login")
input(type="hidden", name="_csrf", value=csrftoken)
button(type="submit") Login
I recommend you to follow Adam Baldwin he writes the lift security blog about security in node.js You can find a secure express skeleton in his repo.