[我正在Django中构建测试应用程序,该应用程序使用模块Django RestFramework API Key生成api密钥。 (请参阅此处:https://florimondmanca.github.io/djangorestframework-api-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函数。