Skip to content

Instantly share code, notes, and snippets.

@gildean
Created May 11, 2013 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gildean/5559948 to your computer and use it in GitHub Desktop.
Save gildean/5559948 to your computer and use it in GitHub Desktop.
Express with csrf tokens. (Note: the main.jade goes to a dir named 'views' under the dir where the app.js resides.)
var express = require('express'),
app = express(),
server = require('http').createServer(app).listen(9999);
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'secret' }));
app.use(express.csrf());
app.locals.pretty = true;
app.use(getToken);
app.post('/save', saveEdit);
app.get('/', mainView);
app.use(function (req, res, next) {
next(new Error('Not found'));
});
app.use(function (err, req, res, next) {
res.send((err.status || 500), err.message);
});
function getToken(req, res, next) {
res.locals.token = req.session._csrf;
next();
}
function saveEdit(req, res, next) {
res.send(200, 'Post had the correct token: ' + req.body._csrf + ' and the value: ' + req.body.name);
}
function mainView(req, res, next) {
res.render('main');
}
!!!
body
h2 correct post
form(action="/save", method="post")
input(type="text", name="name", placeholder="name")
input(type="hidden", name="_csrf", value="#{token}")
input(type="submit", value="save correct")
h2 incorrect post
form(action="/save", method="post")
input(type="text", name="name", placeholder="name")
input(type="submit", value="save incorrect")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment