問題描述
何時使用隱藏字段,何時使用標題以及為什么?X-XSRF_TOKEN
什么時候使用?X-CSRF TOKEN
我們什么時候使用?
When use hidden field and when use header and why ?
X-XSRF_TOKEN
when we use?
X-CSRF TOKEN
when we use?
推薦答案
所有這些都是為了跨站點請求偽造保護,并且您只需要使用其中一個即可向后端發送請求.不同的名稱來自不同的框架.
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.
這一切都是關于向后端發送一個 csrf 值
.然后后端會將其與該特定用戶的數據庫中存儲的 csrf 值進行比較,如果匹配,則允許處理請求.
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 表單時在后端生成.
- 我們無法直接在 html 表單中設置請求頭,因此一種簡單的方法是通過表單輸入將其作為隱藏字段發送.
- 你可以隨意命名這個隱藏的輸入.例如
x-csrf-token:
- 它被添加到請求ajax請求的頭.
- 要使用它,我們可以在渲染 html 時將
csrf 值
放在一個元標記中,然后在前端我們可以從該元標記中獲取值并將其發送到后端.莉>
- 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
作為后端時.Laravel 會自動檢查此標頭并將其與數據庫中的有效csrf 值
進行比較.(laravel 有一個中間件)
- 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:
- 它被添加到請求ajax請求的頭.
- angular 和
axios
等流行庫,會自動從xsrf-token
cookie 中獲取此標頭的值并將其放入每個請求標頭中. - 要使用它,我們應該在后端創建一個名為
xsrf-token
的 cookie,然后我們使用 angular 或 axios 的前端框架會自動使用它.
- 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:
- 因為它很受歡迎,所以 Laravel 在每個響應中都會創建這個 cookie.
- 所以當你使用
axios
或angular
和laravel
時,你不需要做任何事情.只需登錄用戶,'auth' 中間件就可以完成這項工作. - 在 laravel 中,與
x-csrf-token
相比,它是一個更大的字符串,因為 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.
這篇關于X-XSRF-TOKEN 和 X-CSRF-TOKEN 有什么區別?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!