Search code examples
djangopython-3.xdjango-rest-frameworkauthorizationtoken

Unable to get user id with token by django rest framework?


I am using django Django=2.1.7 and rest framework djangorestframework=3.9.2 This is my url for login

path('rest-auth/', include('rest_auth.urls')),

After authentication I got token but I need user id too. I tried to override the post method of rest_framework.authtoken.views.py file with the following code

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        context = {
            'token': token.key,
            'user': user.id
        }
        return Response({'context': context})

Please help me figure out how to get user id with the token. This is my college project.

Note: I find many answers on stack overflow but none is helpful.


Solution

  • Use this Django RestFramework token authentication in order to use authentication. Here you can see how to authenticate, however if you want to use token authentication by default for all views you should add it in settings.py file as :

    REST_FRAMEWORK = {
       'DEFAULT_AUTHENTICATION_CLASSES': (
           ...
           'rest_framework.authentication.TokenAuthentication',
           ...
        ),
    }
    

    or you should add it manually to views which requires token authentication. And in this views you can get authenticated user as request.user or self.request.user.

    from rest_framework.authentication import TokenAuthentication
    
    class ViewSetName(ViewSet):
        authentication_classes = [TokenAuthentication]