每次用户登录时,更改TokenAuthentication的令牌 [英] Change token for TokenAuthentication each time user logs in

查看:136
本文介绍了每次用户登录时,更改TokenAuthentication的令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在每次用户登录时撤销先前的令牌,这意味着生成一个新的令牌(或者至少改变现有的模型实体的密钥)。这听起来很简单,但是在DRF文档中,我没有提到这种情况。文档似乎假定令牌始终保持不变。这只是一个简单的例子,还是我错过了什么?我的问题是:每次用户登录时更改令牌是否有问题?

解决方案

旨在用于令牌永远不需要更改的简单情况,用户只能有一个令牌。


文档似乎假定令牌始终保持不变。


是正确的。任何额外的都必须独立执行。


我想在每次用户登录时撤消先前的令牌。


您可以通过删除登录用户的任何令牌来在身份验证视图中执行此操作。


$ b $导入令牌

Token.objects.filter(user = the_user).delete()

如果您使用提供令牌认证的视图,则需要将它们子类总是为用户获取一个新的令牌。

 类ObtainAuthToken(APIView):
throttle_classes =()
permission_classes =()
parser_classes =(parsers.FormParser, parsers.MultiPartParser,parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)

def post(self,request):
serializer = AuthTokenSerializer(data = request.data)
serializer.is_valid(raise_exception = True)
user = serializer.validated_data ['user']

Token.objects.filter(user = the_user).delete()
令牌,已创建= Token.objects.create(user =用户)

返回响应({'token':token.key})

这将永远无效上一个键并生成一个新的键。


I'd like to revoke the prior token each time a user logs in. That would mean generating a new token (or at least changing the key of existing model entity). It all sounds straightforward, but in the DRF docs, I don't see any mention of that scenario. The docs seem to assume that the token always stays the same. Is that just a simple case, or am I missing something? My question is: Is there something wrong with changing the token each time a user logs in?

解决方案

The TokenAuthentication provided by Django REST Framework is intended to be used for simple cases where the token never needs to change, and there is only a single token for a user.

The docs seem to assume that the token always stays the same.

This is correct. Anything extra has to be implemented independently.

I'd like to revoke the prior token each time a user logs in.

You can do this in the authentication view by removing any tokens for the user who is logged in.

from rest_framework.authtoken.models import Token

Token.objects.filter(user=the_user).delete()

If you are using the views provided for token authentication, then you will need to subclass them to always get a new token for the user.

class ObtainAuthToken(APIView):
    throttle_classes = ()
    permission_classes = ()
    parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
    renderer_classes = (renderers.JSONRenderer,)

    def post(self, request):
        serializer = AuthTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']

        Token.objects.filter(user=the_user).delete()
        token, created = Token.objects.create(user=user)

        return Response({'token': token.key})

This will always invalidate the previous key and generate a new key.

这篇关于每次用户登录时,更改TokenAuthentication的令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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