我想使用Django Rest Framework auth,但我希望为一个用户提供多个令牌。为了做到这一点,我需要实现自己的Token模型,我在Token身份验证类中找到了它:
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
?
答案 0 :(得分:8)
在type="submit"
中定义您自己的身份验证方法:
settings.py
在REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'my_project.my_app.authentication.MyOwnTokenAuthentication',
),
}
:
authentication.py
在from rest_framework.authentication import TokenAuthentication
from my_project.my_app.models.token import MyOwnToken
class MyOwnTokenAuthentication(TokenAuthentication):
model = MyOwnToken
:
models.py
答案 1 :(得分:5)
该消息的含义是,模型Token
可以与任何其他模型交换,只要它具有属性key
和user
即可。这样,例如,如果您想要一种更复杂的方式来生成令牌密钥,您可以定义自己的模型。
因此,如果您需要自定义令牌模型,则应执行以下操作:
rest_framework.authtoken.models
子类化令牌模型。在此处添加您想要的任何自定义行为,但请确保它具有key
属性和user
属性。rest_framework.authentication
对TokenAuthentication类进行子类化。将其model
属性设置为您的新Token模型。