Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user object from token string in DRF?

I have a token string from Django REST Framework's TokenAuthentication.

I need to get the corresponding user object. How would I go about doing this?

like image 269
Berry Avatar asked May 27 '17 01:05

Berry


4 Answers

from rest_framework.authtoken.models import Token
user = Token.objects.get(key='token string').user
like image 172
aliva Avatar answered Sep 20 '22 19:09

aliva


A better method to use would be to simply call request.user since access to the Token means an authenticated request. DjangoRestFramework gives access to request.auth and request.user on a successful TokenAuthentication.

like image 35
Raghav Kukreti Avatar answered Sep 21 '22 19:09

Raghav Kukreti


If you invoke the user object directly from the Token class, as presented in @aliva's solution, you will get a raw partial Django User with just the fields living in the database. If you need to get the real user object, with e.g. its computed properties, you can do this:

from rest_framework.authtoken.models import Token

user_id = Token.objects.get(key=request.auth.key).user_id
user = User.objects.get(id=user_id)
like image 26
manuhortet Avatar answered Sep 21 '22 19:09

manuhortet


Suppose you wanna get userid and username when obtain auth token in Django Rest Framework

More info can get from https://www.django-rest-framework.org/api-guide/authentication/#by-exposing-an-api-endpoint

# in views.py
from rest_framework.auth.models import Token
from rest_framework.auth.views import ObtainToken
from rest_framework.response import Response

class MyObtainToken(ObtainToken):
   """Return User Info along with token"""
   def post(self, request, *arg, **kwarg)
       serializer = self.serializer_class(request.data, context={'request':request})
       serializer.is_valid(raise_exception=True)
       user = serializer.valided_data['user']
       token, _ = Token.objects.get_or_create(user)
       return Response(
            {
                 'token': token.key,
                 'username': user.username,
                 'userid': user.pk
            })
# in urls.py
urlpatterns += [path(r'api/obtain_auth_token', MyObtainToken.as_view()]
like image 24
wllbll Avatar answered Sep 22 '22 19:09

wllbll