drf django rest auth how to expire or delete token?

Manish Gupta picture Manish Gupta · Jun 10, 2016 · Viewed 12.8k times · Source

I am trying to implement authentication using django-rest-framework and django-rest-auth by tivix (link to documentation). I created a user using django shell like:

from django.contrib.auth.models import User
user = User.objects.create_user(username='foo', email='[email protected]', password='bar')
user.save()

Then According to Documentation I logged in a user using django-rest-auth like (Terminal Command):

curl -X POST -d "username=foo&password=bar&[email protected]" http://127.0.0.1:8000/rest-auth/login/

and it returned a token and I know the user is authenticated.

Now I signed out using method described in documentation of django-rest-auth and I can still see the token present in the database. Then I logged in again and it returned the same token as key.

So is there any way by which the token changes or better is deleted every time the user logs out. Also there is no mention in documentation if the token itself will expire(delete automatically) after certain time has passed.

If no such thing is possible, how can I delete the token in both cases?

EDIT : LOGIN & LOGOUT CODE

urls.py (main):

url(r'^rest-auth/', include('rest_auth.urls')),

settings.py:

INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    ...
]

Login CURL Command: (GIVEN ABOVE). Login Command Response:

{u'key': u'e41f0a1c2f5e55569df1c41d1d5d4efb77beddee'}

Logout CURL Command:

curl -X POST -d "key=e41f0a1c2f5e55569df1c41d1d5d4efb77beddee" http://127.0.0.1:8000/rest-auth/logout/

Logout Response:

{u'success': u'Successfully logged out.'}

Answer

varnothing picture varnothing · Jun 10, 2016

You have to be logged in to delete the Token.

Here is how django-rest-auth handle log out (ref):

def post(self, request):
    return self.logout(request)

def logout(self, request):
    try:
        request.user.auth_token.delete()
    except (AttributeError, ObjectDoesNotExist):
        pass

    logout(request)

    return Response({"success": _("Successfully logged out.")},
                    status=status.HTTP_200_OK)

So to logout :

curl -X POST -H "Authorization: Token <token>" http://127.0.0.1:8000/rest-auth/logout/

Please note that django-rest-auth support session based and DRF Token Authentication.

Here is doc about DRF Token Authentication and how to use it

Edit

Added info about DRF Token Authentication