简体   繁体   English

如何在Django Rest Framework中使用自定义令牌模型

[英]How to use custom token model in Django Rest Framework

I'd like to use Django Rest Framework auth but I want to have more than one token for one user. 我想使用Django Rest Framework身份验证,但我想为一个用户使用多个令牌。 In order to do that I need to implement my own Token model, I found this in Token authentication class: 为此,我需要实现自己的令牌模型,我在令牌认证类中找到了这一点:

class TokenAuthentication(BaseAuthentication):
    """
    Simple token based authentication.
    ...
    """

    model = Token
    """
    A custom token model may be used, but must have the following properties.

    * key -- The string identifying the token
    * user -- The user to which the token belongs
    """

But I don't have an idea how I can specify this model. 但是我不知道如何指定此模型。 Should I subclass TokenAuthentication ? 我应该TokenAuthentication吗?

Define you own authentication method in settings.py : settings.py定义您自己的身份验证方法:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'my_project.my_app.authentication.MyOwnTokenAuthentication',
     ),
}

In authentication.py : authentication.py

from rest_framework.authentication import TokenAuthentication
from my_project.my_app.models.token import MyOwnToken

class MyOwnTokenAuthentication(TokenAuthentication):
    model = MyOwnToken

In models.py : models.py

import binascii
import os

from django.db import models
from django.utils.translation import ugettext_lazy as _
from my_project.companies.models import Company


class MyOwnToken(models.Model):
    """
    The default authorization token model.
    """
    key = models.CharField(_("Key"), max_length=40, primary_key=True)

    company = models.OneToOneField(
        Company, related_name='auth_token',
        on_delete=models.CASCADE, verbose_name="Company"
    )
    created = models.DateTimeField(_("Created"), auto_now_add=True)

    class Meta:
        verbose_name = _("Token")
        verbose_name_plural = _("Tokens")

    def save(self, *args, **kwargs):
        if not self.key:
            self.key = self.generate_key()
        return super(MyOwnToken, self).save(*args, **kwargs)

    def generate_key(self):
        return binascii.hexlify(os.urandom(20)).decode()

    def __str__(self):
        return self.key

What that message is saying is that the model Token can be swapped out with any other model, as long as it has properties key and user . 该消息的意思是,只要模型Token具有属性keyuser ,就可以将其与其他任何模型互换。 That way, if, for instance, you want a more complicated way to generate token keys, you can define your own model. 这样,例如,如果您想要一种更复杂的方式来生成令牌密钥,则可以定义自己的模型。

So if you want a custom Token model, you should do the following: 因此,如果您想要自定义令牌模型,则应执行以下操作:

  1. Subclass the Token model from rest_framework.authtoken.models . rest_framework.authtoken.models令牌模型。 Add whatever custom behavior you want here, but make sure it has a key property and user property. 在此处添加您想要的任何自定义行为,但请确保它具有key属性和user属性。
  2. Subclass the TokenAuthentication class from rest_framework.authentication . rest_framework.authentication TokenAuthentication类。 Set its model property to whatever your new Token model is. 将其model属性设置为新的令牌模型。
  3. Make sure to reference your new authentication class in whatever views you want. 确保在所需的任何视图中引用新的身份验证类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 自动将用户令牌分配给自定义配置文件模型 django rest 框架 - Automatically assigning User token to custom profile model django rest framework 如何在 django-rest-framework-simple-jwt 中使用自定义模型用户 - how to use custom model user in django-rest-framework-simple-jwt Django Rest 框架自定义令牌认证 - Django Rest Framework custom token authentication 如何使用Django REST Framework返回模型对象的自定义列表? - How to return a custom list of Model objects using Django REST Framework? 如何在Django Rest API框架中登录自定义用户模型 - how to login a Custom User Model in django rest API framework 如何在 django rest 框架中从 model 制作自定义序列化程序? - How to make custom serializer from model in django rest framework? Django rest 框架不验证自定义用户模型 - Django rest framework not authenticating custom user model 如何使用Django REST框架与外键的默认值模型? - How to use Django REST framework with a model with default value for foreign key? 基础:如何在Django Rest框架中使用PATCH方法用户模型 - Basic: How to use PATCH Method User Model in Django Rest Framework Django Rest Framework,如何使用serializers.ListField with model 和视图? - Django Rest Framework, how to use serializers.ListField with model and view?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM