Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does default_token_generator store tokens?

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?

like image 882
Xen_mar Avatar asked Sep 15 '17 08:09

Xen_mar


Video Answer


1 Answers

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.

like image 132
knbk Avatar answered Oct 08 '22 20:10

knbk