python - How to create self defined token in Django Token Auth
问题描述
Can we create a self-defined token in the Token Auth in Django?
Currently, we are creating a super-user and generating a token for that super-user. But there are several environments and we want to keep the token same for all environments. Hence, a self-defined token is needed.
For example, if we create token using Token Auth
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
we first create a superuser, then we create a token using django-admin.
Authorization:Token 8b000baba908hh7cf0618d492896e7b4bd6c9ce3
Here, I want to define my own token which will be saved in the same table.
解决方案
If I understand correctly your question, you would like to have the same token for superuser in many environments (different servers)? If that's true, then you can try to override the method for automatic creation the tokens.
How to generate the tokens: https://www.django-rest-framework.org/api-guide/authentication/#generating-tokens
DRF AuthToken code https://github.com/encode/django-rest-framework/blob/master/rest_framework/authtoken/models.py
Based on the above the example code can be (not tested):
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
if instance.is_superuser:
Token.objects.create(user=instance, key="superuser_key")
else:
Token.objects.create(user=instance) # use generated key
Important Please do not hardcode the token in the code, you can use for example python-decouple package to handle it as env variable.
推荐阅读
- r - 将“7-2014”转换为日期格式并在 R 中找到最小值
- java - 原因:不存在类型变量 T 的实例,因此 int[] 符合 T[]
- cognos - Cognos 数据源连接问题
- mongodb - MongoDB 基于文档值而不是显式条件匹配数组
- java - 使用 MockMvc StandaloneSetup 时 MockBean 未初始化服务 bean
- html - 坚持使用媒体查询
- c++ - 如何将音频数据放入 AVFrame 进行编码
- android - 发送 Intent.extra 参数时 Koin 崩溃时的 stateViewModel 注入
- html - 删除值时反应样式化组件输入值变为非
- python - 插入枚举列的 Postgres 数组时,SQLAlchemy 引发错误