Change the token for TokenAuthentication every time a user logs in

I would like to revoke the previous token every time a user logs in. This would mean creating a new token (or at least changing the key of an existing model object). This all sounds simple, but in the DRF docs I don't see any mention of this scenario. The docs seem to suggest that the token always stays the same. Is this just a case, or am I missing something? My question is: is there something wrong with the token change every time a user logs in?

+7
django-rest-framework
source share
1 answer

TokenAuthentication provided by the Django REST Framework is intended for use in simple cases where the token never needs to be changed and there is only one token for the user.

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

It is right. All that is needed must be implemented independently.

I would like to revoke the previous token every time a user logs in.

You can do this in authentication mode by deleting all tokens for the user who is logged in.

 from rest_framework.authtoken.models import Token Token.objects.filter(user=the_user).delete() 

If you use the views provided for token authentication, you 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 always overrides the previous key and generates a new key.

+12
source share

All Articles