2

我正在 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

4

1 回答 1

0

查看 à 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

重要说明:我建议您设置自己想要的PASSWORD_HASHERS ,而不是覆盖hash和函数verify

于 2019-10-16T05:39:07.993 回答