The Token key in Auth Token is not encrypted
Checklist
- [x] Raised initially as discussion #...
- [x] This cannot be dealt with as a third party library. (We prefer new functionality to be in the form of third party libraries where possible.)
- [x] I have reduced the issue to the simplest possible case.
do you have any implementation idea to share?
Hello @auvipy
Just a small contribution from Junior Python Developer. It's possible to use the library cryptography with Fernet algorithm.
Like that:
import base64
from cryptography.fernet import Fernet
from django.conf import settings
FERNET_ENCRYPT_KEY = settings.FERNET_ENCRYPT_KEY
def encrypt_value(value):
if value:
value = str(value)
fernet_key = Fernet(key=FERNET_ENCRYPT_KEY)
encrypted_value = fernet_key.encrypt(value.encode("utf-8"))
encrypted_value = base64.urlsafe_b64encode(encrypted_value).decode("utf-8")
return encrypted_value
def decrypt_value(value):
if value:
value = base64.urlsafe_b64decode(value)
fernet_key = Fernet(key=FERNET_ENCRYPT_KEY)
decrypted_value = fernet_key.decrypt(value).decode("utf-8")
return decrypted_value
But, should included FERNET_ENCRYPT_KEY in .env file or secrets. Something like that.
Hey there,
Thanks for raising this issue. But forgive me for asking, whats the point of encrypting TOKEN key?
But, should included FERNET_ENCRYPT_KEY in .env file or secrets. Something like that.
We can use django's SECRET_KEY variable from settings.py
JWE is not a must have. it just adds more security to your http requests as someone might breach the request channel of a browser and can get hold of the requsts before applying SSL encryption and forwaring them to server (it's possible but very difficult). Source
See... https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
Note: The token authentication provided by Django REST framework is a fairly simple implementation.
For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the Django REST Knox third party package.