Django基础认证流程

Django基础认证流程,django,django-rest-framework,django-authentication,Django,Django Rest Framework,Django Authentication,我的Django REST API具有以下身份验证类: class AuthView(APIView): authentication_classes = (BasicAuthentication,) def post(self, request, *args, **kwargs): login(request, request.user) data = {'testkey':'testvalue'} retu

我的Django REST API具有以下身份验证类:

class AuthView(APIView):
      authentication_classes = (BasicAuthentication,)

      def post(self, request, *args, **kwargs):
          login(request, request.user)
          data = {'testkey':'testvalue'}
          return HttpResponse(json.dumps(data), content_type="application/json")
当凭证正确时,控件将转到post方法(这很好)。 但是,对于不正确的凭据,是否有人可以解释为什么控件没有进入post方法


我想为未经身份验证的请求设置一个自定义HTTP状态码(不能在post中这样做,因为控件不用于未经身份验证的请求),我正在寻找一种合适的方法来实现这一点。

基本身份验证通常由浏览器实现。我希望他们只有在认证通过后才能提交帖子


控件从不进入POST方法,因为Django Rest框架(您在这里使用)将首先使用您指定的
authentication\u类对传入请求进行身份验证,然后再进入
POST
方法(或
get
等,具体取决于请求)

这里使用的
BasicAuthentication
类(这是Django Rest框架的工作方式,如图所示)

这将停止执行流(因此它永远不会到达您的方法),并提前返回错误代码


现在,实现此功能的实际代码位于中,在发出请求时调用。
self.initial()



为了回答您问题的第二部分,Django Rest Framework对应该如何操作非常固执,但您可能可以通过定义自己的身份验证类来自定义状态代码,但我对此表示怀疑。

最后,我扩展了基本身份验证并覆盖了如下身份验证凭据方法:

from rest_framework.authentication import BasicAuthentication
from django.contrib.auth import authenticate

class CustomAuth(BasicAuthentication):

    def authenticate_credentials(self, userid, password):
        """
        Override authenticate_credentials(..) of BasicAuthentication
        """
        user = authenticate(username=userid, password=password)
        '''if user is None or not user.is_active:
            raise exceptions.AuthenticationFailed('Invalid username/password')'''
        return (user, None)
目前看来效果不错。
但是,我不确定这是否是最好的方法

这里的逻辑都发生在处理请求的Django Rest框架内,
post
方法只有在通过身份验证时才被调用(幸运的是,否则很容易忽略身份验证)。我扩展了BasicAuthentication以覆盖authentication\u credentials方法(请参见下面的答案),看起来效果不错。然而,这是正确的方法还是会有任何副作用??