Angular JS Verify CSRF Token in POST Request

前端 未结 3 1784
南笙
南笙 2021-01-29 22:53

I am using AngularJS with Rails. I have the following request which updates users in bulk.

 $http{
    method: \'POST\',
    url: $scope.update_url,
    params:          


        
相关标签:
3条回答
  • 2021-01-29 23:31

    I recently faced the same issue and adding the gem angular_rails_js solved it. To my understanding it creates for every rails controller a cookie with the rails CSRF-TOKEN that will be catch (default $http behaviour) by angular $http.

    0 讨论(0)
  • 2021-01-29 23:38

    If you're wondering how to actually set a XSRF-TOKEN cookie value in Rails this answer has an implementation Rails CSRF Protection + Angular.js: protect_from_forgery makes me to log out on POST

    0 讨论(0)
  • 2021-01-29 23:45

    You can set http headers as explained in the $http service.

    You can set it up globally:

    $httpProvider.defaults.headers.post['My-Header']='value'   (or)
    $http.defaults.headers.post['My-Header']='value';
    

    or for a single request:

    $http({
       headers: {
          'My-Header': 'value'
       }  
    });
    

    Here is an important quote from Angular:

    Cross Site Request Forgery (XSRF) Protection XSRF is a technique by which an unauthorized site can gain your user's private data. Angular provides following mechanism to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie called XSRF-TOKEN and sets it as the HTTP header X-XSRF-TOKEN. Since only JavaScript that runs on your domain could read the cookie, your server can be assured that the XHR came from JavaScript running on your domain.

    To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on first HTTP GET request. On subsequent non-GET requests the server can verify that the cookie matches X-XSRF-TOKEN HTTP header, and therefore be sure that only JavaScript running on your domain could have read the token. The token must be unique for each user and must be verifiable by the server (to prevent the JavaScript making up its own tokens). We recommend that the token is a digest of your site's authentication cookie with salt for added security.

    0 讨论(0)
提交回复
热议问题