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添加到请求头中