我正在 Django 中构建一个测试应用程序,它使用模块 Django RestFramework API Key 生成 api key 。 (引用此处:https://florimondmanca.github.io/djangorestframework-api-key/)
我想在生成的 key 中间包含一些符号或连字符。
我已经尝试了模块中的默认 key 生成器,但我想让它更安全。
#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()
输出:
前缀 = jlxGg6bnRdjtrW3Xr6Q6yUMKWAuc0D2u
最佳答案
寻找à KeyGenerator源,您可能想要覆盖您的 KeyGenerator
类。
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()
然后,在您的代码中,使用 CustomKeyGenerator
而不是 KeyGenerator
重要说明:与其覆盖hash
和verify
函数,我建议您设置自己想要的PASSWORD_HASHERS。
关于django - 还有另一种方法可以在 Django 中生成 api key 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58406078/