Get Authenticated user from token in Django Rest Framework

后端 未结 2 811
陌清茗
陌清茗 2021-02-05 05:01

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:

2条回答
  •  时光说笑
    2021-02-05 05:36

    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)
    

提交回复
热议问题