Change token for TokenAuthentication each time use

2020-02-05 09:53发布

问题:

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?

回答1:

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.