django - 还有另一种方法可以在 Django 中生成 api key 吗?

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

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

重要说明:与其覆盖hashverify 函数,我建议您设置自己想要的PASSWORD_HASHERS

关于django - 还有另一种方法可以在 Django 中生成 api key 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58406078/

相关文章:

python - 你如何为 Windows 部署 Django 应用程序?

django - 字段可通过 Django shell 使用,但不能通过 Web 应用程序使用

android - 向应用程序的 Google Cloud Endpoints 2 API 提供 API key 的正确方法是什么?

reactjs - 使用 Next.js 和 Vercel 隐藏 api key 的最简单方法?

tomcat - GCM 在服务器发送消息时出错

python - 使用“in range(len()%4)”在 Django 中循环

python - 在 sendgrid 中发送多封动态模板电子邮件时个性化字段错误

python - 通过代理创建的Django用户无法登录

python - Django-rest-framework API 测试 403 {'detail' : 'You do not have permission to perform this action.' }

python - models.ForeignKey 字段未显示在可浏览的 API 中