what is the difference between X-XSRF-TOKEN and X-CSRF-TOKEN?

浪子不回头ぞ 提交于 2019-12-18 13:06:13

问题


When use hidden field and when use header and why ?
X-XSRF_TOKEN when we use?
X-CSRF TOKEN when we use?


回答1:


when you are submitting your data using ajax you will need headers for CSRF token because ajax will not send the token along with the data.

You can use hidden field for ajax request with following code

$.ajaxSetup(
{
    headers:
    {
        'X-CSRF-Token': $('input[name="_token"]').val()
    }
});

but you will have to add hidden field for every ajax requests.

The difference between the X-CSRF-TOKEN and X-XSRF-TOKEN is that the first uses a plain text value and the latter uses an encrypted value, because cookies in Laravel are always encrypted. If you use the csrf_token() function to supply the token value, you probably want to use the X-CSRF-TOKEN header.

its removed in laravel 5.2 doc but you can find it in laravel 5.0 doc, link is here




回答2:


All of them are for cross site request forgery protection and you need to use just one of them when sending a request to backend.

csrf :

  • Used in html forms (not ajax)
  • we can not set request header in html forms directly, so we have to send it via form input as a hidden field.

x-csrf-token:

  • It is added to request header for ajax requests.
  • When using laravel as backend. laravel checks this header automatically and compares it to valid csrf in database.

x-xsrf-token:

  • It is added to request header for ajax requests.
  • Popular libraries like angular and axios, automatically get value of this header from xsrf-token cookie and send it with every request.
  • Because it's popular, laravel creates this cookie in each response.
  • so when you're using for example axios and laravel you don't need to do anything. just logged in user and 'auth' middleware will do the job.
  • Its a bigger string compared to x-csrf-token because cookies are encrypted in laravel.


来源:https://stackoverflow.com/questions/42408177/what-is-the-difference-between-x-xsrf-token-and-x-csrf-token

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