问题
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
laravelas backend.laravelchecks this header automatically and compares it to validcsrfin 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 fromxsrf-tokencookie and send it with every request. - Because it's popular, laravel creates this cookie in each response.
- so when you're using for example
axiosandlaravelyou 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-tokenbecause cookies are encrypted inlaravel.
来源:https://stackoverflow.com/questions/42408177/what-is-the-difference-between-x-xsrf-token-and-x-csrf-token