Django Restframework _自定义身份验证

时间:2018-05-19 14:21:42

标签: python django django-rest-framework

我用这种结构编写了一些自定义身份验证代码: serializers.py

class LoginSerializer(serializers.Serializer):
    first_token = serializers.CharField()
    phonenumber = serializers.CharField()
    token = serializers.CharField(max_length=255, read_only=True)

观看.py

class LoginView(APIView):
    serializer_class = LoginSerializer
    permission_classes = (AllowAny,)
    def post(self, request, format=None):
        phonenumber = request.data.get('phonenumber', None)
        first_token = request.data.get('first_token', None)
        try:
            x = User.objects.get(phonenumber=phonenumber)
        except x.DoesNotExist:
            return Response('user does not exists')
        if first_token == x.first_token.token:
            user = authenticate(phonenumber=phonenumber)
            login_user = login(request, user)
            user_info = {
                'phonenumber': user.phonenumber,
                'username': user.username,
                'token': user.token,
                'is_admin':user.is_admin,
            }

            return Response(user_info, status=status.HTTP_200_OK)

urls.py

urlpatterns = [
    re_path(r'^login/$', views.LoginView.as_view(), name='login'),
]

因此,身份验证和登录成功并且用户登录。但是当我尝试转到另一个页面时,testframework不会存储身份验证。我已经进行了自定义身份验证。 auth.py

class PhoneAuthentication(authentication.BaseAuthentication):
    authentication_header_prefix = 'Token'
    def authenticate(self, request):
        request.user = None
        auth_header = authentication.get_authorization_header(request).split()
        auth_header_prefix = self.authentication_header_prefix.lower()
        if not auth_header:
            return None
        if len(auth_header) == 1:
            return None
        elif len(auth_header) > 2:
            return None
        prefix = auth_header[0].decode('utf-8')
        token = auth_header[1].decode('utf-8')
        if prefix.lower() != auth_header_prefix:
            return None
        return self._authenticate_credentials(request, token)

    def _authenticate_credentials(self, request, token):
        try:
            payload = jwt.decode(token, settings.SECRET_KEY)
        except:
            raise exceptions.AuthenticationFailed("invalid authentication . could not decode token")
        try:
            user = User.objects.get(pk=payload['id'])
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')
        return(user, token)

1 个答案:

答案 0 :(得分:0)

我认为最好的方法是subscribe默认为DRFvar albums = [Album]() let request = NSFetchRequest<Album>(entityName: "Album") request.predicate = NSPredicate(format: "recordArtist.name = %@", "<ProvideArtistNameHere>") do { albums = try context.fetch(request) if albums.count > 0 { // You have found cover } } catch { print("Error = \(error.localizedDescription)") } 视图。