How to implement CSRF protection in Ajax calls using express.js (looking for complete example)? How to implement CSRF protection in Ajax calls using express.js (looking for complete example)? ajax ajax

How to implement CSRF protection in Ajax calls using express.js (looking for complete example)?


It can be done by adding meta tag for CSRF token and then pass CSRF token with every Ajax request

Server

Add CSRF middleware

app.use(express.csrf());app.use(function (req, res, next) {  res.locals.token = req.session._csrf;  next();});

You can pass a CSRF token to the client side via, say, a meta tag. For ex, in Jade

meta(name="csrf-token", content="#{token}")

Client

jQuery has a feature called ajaxPrefilter, which lets you provide a callback to be invoked every Ajax request. Then set a header using ajaxPrefilter.

var CSRF_HEADER = 'X-CSRF-Token';var setCSRFToken = function (securityToken) {  jQuery.ajaxPrefilter(function (options, _, xhr) {    if (!xhr.crossDomain) {      xhr.setRequestHeader(CSRF_HEADER, securityToken);    }  });};setCSRFToken($('meta[name="csrf-token"]').attr('content'));


server.js

...// All Cookies/Sessions/BodyParser go firstapp.use(express.csrf());...// Get the requestapp.post('/ajax', function(req, res){    res.render('somelayout', {csrf_token: req.session._csrf});});

In somelayout.jade

input(type='hidden', name='_csrf', value=csrf_token)

The CSRF middleware only generates the csrf token once per session, so it will probably not change for the duration of a user's visit.

Also, it doesn't check for the token on GET and HEAD requests. As long as the token is in the request (header, body, or query), you're good. That's pretty much all there is to it.


Since you are using Backbone.js for your application, I am assuming that it is a SPA and you initially load an index.html file, then make any other requests are made via ajax calls. If so, you can add a small snippet of JS code to your index.html file to hold the crsf token for any future ajax calls.

For example:

index.html (using Handlebars for templating...)

<!DOCTYPE html><html>    <head>        ...        <script type="text/javascript">            $( function() {                window.Backbone.csrf = "{{csrfToken}}";            });        </script>    </head>    <body>        ...    </body></html>

When you render the index.html file, give it the csrf token that the express framework generated here: req.session._csrf

When you use Backbone.js, it sets a global variable called Backbone. All that the previous function is doing is seting a property called csrf to the global Backbone object. And when you make an ajax call to POST data, simply add the Backbone.csrf variable to the data as _csrf that is being sent via the ajax call.