Get user object from token string in DRF?

后端 未结 5 877
说谎
说谎 2021-02-09 16:01

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?

5条回答
  •  爱一瞬间的悲伤
    2021-02-09 16:55

    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()]
    

提交回复
热议问题