Get Authenticated user from token in Django Rest Framework

All we need is an easy explanation of the problem, so here it is.

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

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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)

Method 2

In my case, I am trying to test my API with an API REST Client. When I put the Header in the configuration, it works.

Authorization: Token <<token>>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply