Is there another way to generate api key in django?

Viewed 1799

I'm building a testing application in Django that generates api key using the module Django RestFramework API Key. (Refer here: https://florimondmanca.github.io/djangorestframework-api-key/)

I want to include some symbols or hyphen in the middle of the generated key.

I have tried the default key generator in the module but I want to make it more secure.


#models.py

from rest_framework_api_key.models import BaseAPIKeyManager
from rest_framework_api_key.crypto import KeyGenerator
from rest_framework_api_key.models import AbstractAPIKey

class UserCompanyAPIKeyManager(BaseAPIKeyManager):
    key_generator = KeyGenerator(prefix_length=32, secret_key_length=32)

class UserCompanyAPIKey(AbstractAPIKey):
    objects = UserCompanyAPIKeyManager()

Output:

Prefix = jlxGg6bnRdjtrW3Xr6Q6yUMKWAuc0D2u

1 Answers

Looking à KeyGenerator source, you might want to override your KeyGenerator class.

class CustomKeyGenerator(KeyGenerator):
    def get_prefix(self) -> str:
        return 'your_prefix'

    def get_secret_key(self) -> str:
        return 'your_secret_key'

    # Below, you can modify the way your "hasher" works, 
    # but I wouldn't play with that as it's native django's auth' hasher.

    def hash(self, key: str) -> str:
        #your hashing algorithm
        return 'your_hashed_key'

    def verify(self, key: str, hashed_key: str) -> bool:
        #checking given key
        return bool()

Then, within your code, use CustomKeyGeneratorinstead of KeyGenerator

Important note: Instead of overriding hash and verify function's, I'd recomend you setup your own wanted PASSWORD_HASHERS

Related