Framework中的令牌获取经过身份验证的用户

Framework中的令牌获取经过身份验证的用户

本文介绍了从Django Rest Framework中的令牌获取经过身份验证的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django的新手,我设法使用DRF构建了一个小型API.我在我的angular.js客户端发布了用户身份验证详细信息,DRF返回了一个看起来像这样的令牌:

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' }

基于教程,我应该从request.user检索详细信息但是我不知道在哪里做.我发现它令人困惑,因为它没有给出很好的例子.有人对如何解决有想法吗?非常感谢您的投入.

Based on the tutorial, I am supposed to retrieve the details from request.userBut 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

序列化器

 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

推荐答案

请记住,我也是Angular和DRF的新手...

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

如果您已经收到令牌,则在angularjs端,您需要将令牌包括在后续请求的标头中.也许像这样的身份验证请求中的缩写代码:

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;
});

您可能需要在ViewSet中

In your ViewSet you would likely want

authentication_classes = (TokenAuthentication,)

以及所有相关的权限类.

along with whatever permission_classes are relevant.

如果您将Token包含在Angular http请求中,那么我相信您可以使用request.user来引用用户,例如

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)

或者,这是另一种用途(用户模型为django.contrib.auth.models.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)

这篇关于从Django Rest Framework中的令牌获取经过身份验证的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 01:22