CSURF Angular Implementation

三世轮回 提交于 2019-12-19 09:06:05

问题


I have been trying to do a csurf implementation on a personal project I have been working on. I have been searching google all over the place to try to figure out how to implement csurf on a form when I am not using a templating engine like Jade or EJS. My express server is also not directly rendering the pages but is mainly returning JSON. I have all of my front end being referenced like so

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

my server code that is using the csurf looks like this

app.use(csurf());

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

On the front end for the form the html input field looks like this. I am also using AngularJS and based on examples I have seen all I should have to do is this.

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

I am getting the following error in the terminal

Error: invalid csrf token

If I inspect the hidden input this is what is displayed.

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

回答1:


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

e.g.

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

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

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

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




回答2:


According to section "Cross Site Request Forgery (XSRF) Protection" of $http documentation:

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

So, you need just to configure csurf module to use that cookie. Like that:

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();
});
...

Doing so, you don't need to configure your AngularJS stuff and create hidden inputs.



来源:https://stackoverflow.com/questions/27910409/csurf-angular-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!