How does default_token_generator store tokens?

折月煮酒 提交于 2019-12-10 09:32:54

问题


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)

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)

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?


回答1:


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 hash combines four values:

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

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.

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.



来源:https://stackoverflow.com/questions/46234627/how-does-default-token-generator-store-tokens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!