【问题标题】:Is there another way to generate api key in django?还有另一种方法可以在 django 中生成 api 密钥吗?
【发布时间】:2019-10-16 05:07:45
【问题描述】:

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

【问题讨论】:

    标签: django django-rest-framework api-key key-generator


    【解决方案1】:

    查看 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,而不是覆盖 hashverify 函数。

    【讨论】:

      猜你喜欢
      • 2022-12-24
      • 1970-01-01
      • 2014-03-13
      • 2022-01-16
      • 2013-09-26
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      相关资源
      最近更新 更多