CSURF Angular Implementation

I am trying to implement a csurf implementation on a personal project that I am working on. I've searched google all over the place to try and figure out how to implement a csurf on a form when I'm not using a templating engine like Jade or EJS. My express server also doesn't feed pages directly, but mostly returns JSON. I have everything I refer to so

app.use(express.static(__dirname + '/www'));

      

my server code using csurf is as follows

app.use(csurf());

app.use(function (req, res, next) {
    res.cookie('XSRF-TOKEN', req.csrfToken());
  next();
});

      

In the interface for the form, the html input field looks like this. I am also using AngularJS and based on the examples I have seen, all I have to do is.

<input type="hidden" name="_csrf" value="{{csrftoken}}">

      

I am getting the following error in terminal

Error: invalid csrf token

      

If I check for hidden input, this is what is displayed.

<input type="hidden" name="_csrf" value="">

      

+3


source to share


2 answers


In your controller you need to set the local variable equal to the csrf cookie value

eg.

.controller('YourCtrl', function($cookies, $scope) {
    $scope.csrftoken = $cookies._csrf
  }
);

      



For this example, you will need to include the ngCookies module, so include something like this in index.html

<script src="bower_components/angular-cookies/angular-cookies.js"></script>

      

And then add the "ngCookies" dependency to your module.

+3


source


In accordance with section " Protection of requests for cross-site request (XSRF) " $http

documentation :

When making XHR requests, the $ http service reads the token from the cookie (XSRF-TOKEN by default) and sets it as the HTTP header (X-XSRF-TOKEN).

So, you just need to configure the module csurf

to use this cookie. For example:



var csrf = require('csurf');
...
// Cookie / Session initialization etc
app.use(cookieParser());
...
// Important : csrf should be added after cookie and session initialization.
// Otherwise you will get 'Error: misconfigured csrf'
app.use(csrf());
app.use(function(req, res, next) {
  res.cookie('XSRF-TOKEN', req.csrfToken());
  next();
});
...

      

This way you don't need to customize your AngularJS stuff and create hidden inputs.

Some explanations

+2


source







All Articles