how to implement csrf protection for cross domain requests

后端 未结 3 1847
耶瑟儿~
耶瑟儿~ 2021-01-31 10:30

I have two web apps, one for the Web UI in AngularJS and one for the REST webservices in Java. Both are deployed on separate domains.

The applications uses cookie for au

3条回答
  •  执笔经年
    2021-01-31 10:55

    Angularjs has built-in support for CSRF but unfortunately it doesn't work cross domain, so you have to build your own.

    I managed to get it working by first returning a random token in the headers and cookies on the first request. In order to read the header you need to add it to Access-Control-Expose-Headers. This is then added to all posts

    $http.get('url').
        success(function(data, status, headers) {
            $http.defaults.headers.post['X-XSRF-TOKEN'] = headers('XSRF-TOKEN');
        });
    

    Then on the server you can compare the cookie value with the value in the header to ensure they are the same.

提交回复
热议问题