DRF temporary token authentication

Kapustlo cb1e42028c Added helper scripts 1 year ago
drf_temptoken 4e5f6ede9c Added type hints 1 year ago
scripts cb1e42028c Added helper scripts 1 year ago
tests cb1e42028c Added helper scripts 1 year ago
.gitignore e26f2fbd68 Ignored pyright config 1 year ago
LICENSE bd07e188b0 Initial commit 2 years ago
README.md 9d227181bb Added query param auth 1 year ago
requirements.txt ad09b25031 Added wheel to deps 1 year ago
setup.py 4e5f6ede9c Added type hints 1 year ago



DRF temporary authentication token


pip install drf-temptoken


Include drf_temptoken in INSTALLED_APPS


Add drf_temptoken.auth.TempTokenAuthentication into your authentication classes


Create token for user

from django.contrib.auth import get_user_model
from drf_temptoken.utils import create_token, get_user_tokens

User = get_user_model()

user = User.objects.first()

token = create_token(user)

# Sets token's expiration date to current
token = token.expire()

key = token.key # Used in authentication process

tokens = get_user_tokens(user) # Returns a queryset of TempTokens belonging to the user

Default settings (can be overriden in Django's settings)


TMP_TOKEN_AUTH_HEADER = 'Authorization'

# Set any value in order to get the token from query

# Python's timedelta kwargs passed in order to set token's expiration date
    'days': 7 # Token will be expired in 7 days by default

Auth backend will check for HTTP_AUTHORIZATION: TMP {token} by default

Assuming your token (token.key) is equal to "123", your request should look like this:

import requests

headers = {
    'Authorization': 'TMP 123'

response = requests.get(url, headers=headers)

Or like this if you set query param to _api_key:

import requests

url = 'https://example.com?_api_key=123'

response = requests.get(url)