default_token_generator如何存储令牌? [英] How does default_token_generator store tokens?

查看:91
本文介绍了default_token_generator如何存储令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近使用教程构建了一个基于Django的身份验证系统。在此系统中,我在forms.py中创建了一个令牌。然后,此令牌通过激活激活邮件发送(作为链接)。

I recently built a Django-based authentication system using a tutorial. Within this System I created a token within a forms.py. This Token is then send (as a link) in an activation activation mail.

from django.contrib.auth.tokens import default_token_generator    
token = default_token_generator.make_token(user)

接收到get请求的视图将令牌与该链接中提供的用户ID匹配,并使用以下命令检查令牌:

The view which receives the get request matches the token and the user-id supplied in this link and checks the token using:

default_token_generator.check_token(user, token)

这将验证令牌是通过我的网站发送的。但是我不明白这个过程。令牌是唯一的,但我似乎没有将令牌保存在某个地方?那么 check_token()如何验证令牌?

This verifies that the token was sent though my site. But I don't understand the process. The token is unique but I don't seem to save the token somewhere? So how does check_token()verify the token?

推荐答案

令牌由时间戳和HMAC值组成。 HMAC是带键的哈希函数:哈希使用秘密密钥(默认情况下为 settings.SECRET_KEY )来获取唯一值,但是无论是否使用该密钥, unhashing都是不可能的。

A token consist of a timestamp and a HMAC value. HMAC is a keyed hashing function: hashing uses a secret key (by default settings.SECRET_KEY) to get a unique value, but "unhashing" is impossible with or without the key.

哈希值包含四个值:


  • 用户的主键。

  • 用户的哈希密码。

  • 用户的上次登录时间戳。

  • 当前时间戳。

  • The user's primary key.
  • The user's hashed password.
  • The user's last login timestamp.
  • The current timestamp.

令牌随后由当前时间戳和这四个值的哈希组成。前三个值已经存在于数据库中,第四个值是令牌的一部分,因此Django可以随时验证令牌。

The token then consists of the current timestamp and the hash of these four values. The first three values are already in the database, and the fourth value is part of the token, so Django can verify the token at any time.

包括用户的哈希值密码和哈希中的最后登录时间戳,当用户登录或更改密码时,令牌会自动失效。还检查当前时间戳以查看令牌是否已过期。请注意,即使当前时间戳记包含在令牌中(作为以base36编码的字符串形式),但是如果攻击者更改了值,则哈希值也会随之更改,令牌也将被拒绝。

By including the user's hashed password and last login timestamp in the hash, a token is automatically invalidated when the user logs in or changes their password. The current timestamp is also checked to see if the token has expired. Note that even though the current timestamp is included in the token (as a base36 encoded string), if an attacker changes the value, the hash changes as well and the token is rejected.

这篇关于default_token_generator如何存储令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆