django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

The Token key in Auth Token is not encrypted

Open alisharf opened this issue 3 years ago • 3 comments

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.

alisharf avatar Dec 19 '22 21:12 alisharf

do you have any implementation idea to share?

auvipy avatar Dec 20 '22 08:12 auvipy

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.

alfmorais avatar Feb 13 '23 00:02 alfmorais

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

baseplate-admin avatar Mar 29 '23 06:03 baseplate-admin

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

codespearhead avatar Mar 13 '24 12:03 codespearhead

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.

lovelydinosaur avatar Mar 21 '24 14:03 lovelydinosaur