I'm using the csrf
middleware with the Express framework. My login page is like this:
app.get('/', getUserOrLogin, function (req, res) {
// do something...
});
Where the getUserOrLogin
is:
// Return the user otherwise redirect to login page
var getUserOrLogin = function (req, res, next) {
var user = req.session.user;
if (user == null) {
req.session.backTo = req.originalUrl;
res.redirect('/login');
} else {
req.user = user;
next();
}
};
When I try to access /
it redirects me correctly to /login
but the csrf
token in cookies is not set.
Am I doing something wrong with the getUserOrLogin
function or is an Express bug?
I found the error. Since I don't want csrf
control on every page I was using a conditional function:
// Disable CSRF for some requests
var conditionalCSRF = function (req, res, next) {
var whitelist = ['/inbound'];
if (req.method !== 'POST') {
next();
return;
}
if (whitelist.indexOf(req.url) !== -1) {
next();
} else {
(express.csrf())(req, res, next);
}
};
app.use(conditionalCSRF);
But that function doesn't set the csrf
token until the user requires a page that requires it. So I modified it in that way
var connect = require('connect');
// Disable CSRF for some requests
var conditionalCSRF = function (req, res, next) {
var whitelist = ['/inbound'];
req.session._csrf || (req.session._csrf = connect.utils.uid(24));
if (req.method !== 'POST') {
next();
return;
}
if (whitelist.indexOf(req.url) !== -1) {
next();
} else {
(express.csrf())(req, res, next);
}
};
app.use(conditionalCSRF);