Change token for TokenAuthentication each time user logs in

后端 未结 1 1040
梦毁少年i
梦毁少年i 2020-12-09 21:03

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 s

相关标签:
1条回答
  • 2020-12-09 21:51

    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.

    0 讨论(0)
提交回复
热议问题