django中csrf token的驗證原理

2021-10-01 04:47:23 字數 1879 閱讀 7996

1.django是怎麼驗證csrfmiddlewaretoken合法性的?

2.每次重新整理頁面的時候中的csrf的value都會更新,每次重複登入的時候cookie的csrf令牌都會重新整理,那麼這兩個csrf-token有什麼區別

csrf簡稱跨站請求偽造

django第一次響應來自某個客戶端的請求時,會在伺服器端隨機生成乙個token,把這個token放在cookie裡,然後每次post請求都會帶上這個token,這樣就能避免csrf攻擊

when validating the 『csrfmiddlewaretoken』 field value, only the secret, not the full token, is compared with the secret in the cookie value. this allows the use of ever-changing tokens. while each request may use its own token, the secret remains common to all.

this check is done by csrfviewmiddleware.

官方文件中說道,檢驗token時,只比較secret是否和cookie中的secret值一樣,而不是比較整個token,同一次登入,form表單中的token每次都會變,而cookie中的token不變,以下為原始碼:

def

_compare_salted_tokens

(request_csrf_token, csrf_token)

:# assume both arguments are sanitized -- that is, strings of

# length csrf_token_length, all csrf_allowed_chars.

return constant_time_compare(

_unsalt_cipher_token(request_csrf_token)

, _unsalt_cipher_token(csrf_token),)

def_unsalt_cipher_token

(token)

:"""

given a token (assumed to be a string of csrf_allowed_chars, of length

csrf_token_length, and that its first half is a salt), use it to decrypt

the second half to produce the original secret.

"""salt = token[

:csrf_secret_length]

token = token[csrf_secret_length:

] chars = csrf_allowed_chars

pairs =

zip(

(chars.index(x)

for x in token)

,(chars.index(x)

for x in salt)

) secret =

''.join(chars[x - y]

for x, y in pairs)

# note negative values are ok

return secret

token字串的前32位時salt,後面時加密後的token,通過salt能解密出唯一的secret,django會驗證表單中的token和cookie中token是否能解除同樣的secret,secret一樣則本次請求合法,同樣也不難解釋,為什麼ajax請求時,需要從cookie中拿取token新增到請求頭中

django中restframework巢狀序列化

問題 定義好了序列化器後有沒有遇到過想要序列化的資料表中有外來鍵的情況,我們需要的這個和外來鍵關聯的資料 model.py 報警表 class police models.model 報警型別 police models.charfield max length 50 開始範圍 begin mode...

django基礎 django中的app應用

urlpatterns path lw2 views.lw2 先設定子路由和乙個實現登入功能頁面 login.html 使用者名稱 密碼 通過request.post.get 方法可以返回使用者登入時的資訊,根據資訊來判斷和進行下一事件。如果登入資訊與資料庫中資訊不相匹配,則重新返回新的登入頁面。此...

django 重新整理快取 Django 中的快取問題

django 中的快取問題 簡單介紹 在動態 中,使用者所有的請求,伺服器都會去資料庫中進行相應的增,刪,查,改,渲染模板,執行業務邏輯,最後生成使用者看到的頁面.當乙個 的使用者訪問量很大的時候,每一次的的後台操作,都會消耗很多的服務端資源,所以必須使用快取來減輕後端伺服器的壓力.快取是將一些常用...