I would like to add a CSRF protection in my app which uses a MEAN stack.
I tried the answer already given by someone : CSRF Protection in ExpressJS
But it was for the older express version, so I made some changes :
app.use(cookieParser(config.cookieSecret, { httpOnly: true }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: config.sessionSecret, resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(csrf({value: function(req) {
var token = (req.body && req.body._csrf)
|| (req.query && req.query._csrf)
|| (req.headers['x-csrf-token'])
|| (req.headers['x-xsrf-token']);
return token;
}
}));
app.use(function(req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
next();
});
I can see the token named XSRF-TOKEN
is well generated on my app (using Chrome inspection).
But when I post a form (Angular frontend), I have an error about the token :
{"message":"invalid csrf token","error":{"expose":true,"code":"EBADCSRFTOKEN","statusCode":403,"status":403}}
Did I miss something ? I'm wondering if req.csrfToken()
generates the good token given by Angular...
EDIT :
I just see the XSRF-TOKEN
is used by AngularJS in $http
requests only. So I think I have to add a hidden input in my form to post with csrf value, to be checked by Express, but how ?