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.
Kevin brown
source share