Get Authenticated user from token in Django Rest Framework

26,450

Keeping in mind that I am also new to Angular and DRF...

If you are already receiving the token, then on the angularjs side, you need to be including the token in the headers of your subsequent requests. Perhaps like this abbreviated code from the authentication request:

$http({auth request code here}).then(function(response){
  var token = response.headers().token
  $http.defaults.headers.common['Authorization'] = 'Token ' + token;
});

In your ViewSet you would likely want

authentication_classes = (TokenAuthentication,)

along with whatever permission_classes are relevant.

If you are including the Token in the Angular http request, then I believe you can reference the user with request.user, like perhaps

def list(self, request):
    queryset = SomeObject.objects.filter(owner=request.user)

Or, here is another use (User model is django.contrib.auth.models.User):

class UserView(RetrieveAPIView):
    model = User
    serializer_class = UserSerializer

    def retrieve(self, request, pk=None):
        """
        If provided 'pk' is "me" then return the current user.
        """
        if request.user and pk == 'me':
            return Response(UserSerializer(request.user).data)
        return super(UserView, self).retrieve(request, pk)
Share:
26,450

Related videos on Youtube

Cheruiyot Felix
Author by

Cheruiyot Felix

Cloud and Productivity Specialist

Updated on September 06, 2020

Comments

  • Cheruiyot Felix
    Cheruiyot Felix over 3 years

    I am new in Django and I have managed to build a small API using DRF. I have my angular.js client end posting user auth details and DRF returns a token which looks like this:

    { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
    

    Based on the tutorial, I am supposed to retrieve the details from request.user But I don't know where to do this. I find it confusing since it doesn't give a good example. Anyone with an idea on how go around it? Your input is highly appreciated.

    Below is the code of my view and serializer.

    from serializers import ExampleSerializer
    from models import Example
    from rest_framework import viewsets
    
    class ExampleViewSet(viewsets.ModelViewSet):
        """
        Example api description
        """
        queryset = Example.objects.all()
        serializer_class = ExampleSerializer    
    

    Serializer

     from models import Example
     from rest_framework import serializers
    
     class ExampleSerializer(serializers.ModelSerializer):
          class Meta:
            model = Example
            fields = ('id', 'field_one', 'field_two', 'created_at', 'updated_at')
            depth = 1
    
    • haki
      haki about 10 years
      Take a look at the angular/drf seed - it includes authentication.
    • Cheruiyot Felix
      Cheruiyot Felix about 10 years
      Drf-seed does not provide details like username for the authenticated user but just token to fetch more resources.Please take a look. I want to return user details with this token.
  • Cheruiyot Felix
    Cheruiyot Felix about 10 years
    I have tried to look around and I have resolved this might be the best option. It works for me. Thanks.
  • jmickela
    jmickela over 9 years
    I used this to fix a similar problem, but would recommend overriding get_serializer_class to select the proper serializer, and instead of calling Respond directly from retrieve set the pk like so: self.kwargs["pk"] = request.user.pk pk = request.user.pk That way you change the default behavior as little as possible.
  • Talha
    Talha about 5 years
    So you are telling me that I have to send 'user' in every request? I think it should work like this: If user hit a user info "GET" method call, with token in headers, they should be served with details based on current token bearer (which BE should know which user has this token)