如何在Django Rest框架中使用自定义令牌模型 [英] How to use custom token model in Django Rest Framework

查看:190
本文介绍了如何在Django Rest框架中使用自定义令牌模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Django Rest Framework auth,但是我想为一个用户提供多个令牌。为了做到这一点,我需要实现我自己的令牌模型,我在Token身份验证类中找到了这一点:

I'd like to use Django Rest Framework auth but I want to have more than one token for one user. 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
    """

但是我没有想法如何指定这个模型。我应该把 TokenAuthentication

But I don't have an idea how I can specify this model. Should I subclass TokenAuthentication?

推荐答案

模型令牌可以与任何其他模型交换,只要它具有属性用户。这样,如果你想要一个更复杂的方法来生成令牌键,你可以定义自己的模型。

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. 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. rest_framework.authtoken.models将代码模型子类化。添加您想要的任何自定义行为,但请确保它具有属性和用户属性。

  2. rest_framework.authentication 中将TokenAuthentication类子类化。将其模型属性设置为任何新的令牌模型。

  3. 确保在您想要的任何视图中引用新的身份验证类。

  1. Subclass the Token model from rest_framework.authtoken.models. Add whatever custom behavior you want here, but make sure it has a key property and user property.
  2. Subclass the TokenAuthentication class from rest_framework.authentication. Set its model property to whatever your new Token model is.
  3. Make sure to reference your new authentication class in whatever views you want.

这篇关于如何在Django Rest框架中使用自定义令牌模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆