問題描述
何時(shí)使用隱藏字段,何時(shí)使用標(biāo)題以及為什么?X-XSRF_TOKEN
什么時(shí)候使用?X-CSRF TOKEN
我們什么時(shí)候使用?
When use hidden field and when use header and why ?
X-XSRF_TOKEN
when we use?
X-CSRF TOKEN
when we use?
推薦答案
所有這些都是為了跨站點(diǎn)請(qǐng)求偽造保護(hù),并且您只需要使用其中一個(gè)即可向后端發(fā)送請(qǐng)求.不同的名稱來自不同的框架.
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. Different names come from different frameworks.
這一切都是關(guān)于向后端發(fā)送一個(gè) csrf 值
.然后后端會(huì)將其與該特定用戶的數(shù)據(jù)庫(kù)中存儲(chǔ)的 csrf 值進(jìn)行比較,如果匹配,則允許處理請(qǐng)求.
It's all about sending a csrf value
to backend. Then backend will compare it with the csrf value stored in database for that specific user and if it matches, it will allow processing the request.
csrf :
- 用于 html 表單(不是 ajax)
- 在渲染 html 表單時(shí)在后端生成.
- 我們無法直接在 html 表單中設(shè)置請(qǐng)求頭,因此一種簡(jiǎn)單的方法是通過表單輸入將其作為隱藏字段發(fā)送.
- 你可以隨意命名這個(gè)隱藏的輸入.例如
x-csrf-token:
- 它被添加到請(qǐng)求ajax請(qǐng)求的頭.
- 要使用它,我們可以在渲染 html 時(shí)將
csrf 值
放在一個(gè)元標(biāo)記中,然后在前端我們可以從該元標(biāo)記中獲取值并將其發(fā)送到后端.莉>
- It is added to the request header for ajax requests.
- To use it, we can put the
csrf value
in a meta tag while rendering the html, then in front end we can get the value from that meta tag and send it to backend.
Laravel 特定:
Laravel specific:
- 使用
laravel
作為后端時(shí).Laravel 會(huì)自動(dòng)檢查此標(biāo)頭并將其與數(shù)據(jù)庫(kù)中的有效csrf 值
進(jìn)行比較.(laravel 有一個(gè)中間件)
- When using
laravel
as backend. Laravel checks this header automatically and compares it to the validcsrf value
in database.(laravel has a middleware for this)
x-xsrf-token:
- 它被添加到請(qǐng)求ajax請(qǐng)求的頭.
- angular 和
axios
等流行庫(kù),會(huì)自動(dòng)從xsrf-token
cookie 中獲取此標(biāo)頭的值并將其放入每個(gè)請(qǐng)求標(biāo)頭中. - 要使用它,我們應(yīng)該在后端創(chuàng)建一個(gè)名為
xsrf-token
的 cookie,然后我們使用 angular 或 axios 的前端框架會(huì)自動(dòng)使用它.
- It is added to the request header for ajax requests.
- Popular libraries like angular and
axios
, automatically get value of this header fromxsrf-token
cookie and put it in every request header. - To use it, we should create a cookie named
xsrf-token
in backend, then our front end framework that uses angular or axios will use it automatically.
Laravel 特定:
Laravel specific:
- 因?yàn)樗苁軞g迎,所以 Laravel 在每個(gè)響應(yīng)中都會(huì)創(chuàng)建這個(gè) cookie.
- 所以當(dāng)你使用
axios
或angular
和laravel
時(shí),你不需要做任何事情.只需登錄用戶,'auth' 中間件就可以完成這項(xiàng)工作. - 在 laravel 中,與
x-csrf-token
相比,它是一個(gè)更大的字符串,因?yàn)?cookie 在 laravel 中是加密的.
- Because it's popular, laravel creates this cookie in each response.
- so when you're using for example
axios
orangular
withlaravel
, you don't need to do anything. just log user in and 'auth' middleware will do the job. - In laravel, its a bigger string compared to
x-csrf-token
because cookies are encrypted in laravel.
這篇關(guān)于X-XSRF-TOKEN 和 X-CSRF-TOKEN 有什么區(qū)別?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!