Django Rest Framework Authentication Errors

I'm making an angular app that authenticates in a django site using a rest api. In the doc of drf they state that a denied user authentication will result in two error, HTTP 401 and HTTP 403, as follows:

When an unauthenticated request is denied permission there are two different error codes that may be appropriate.

  • HTTP 401 Unauthorized
  • HTTP 403 Permission Denied
  • Howenever, when I try to authenticate with some dummy data, that is wrong on purpose, I get error response HTTP 400 and with non_field_errors . What is the issue here?

    First I do a simple authentication with the username and the password, this made to get the user token, that will be needed on other operations in the site.

    I'm using a method to obtain an expering auth token, you can see it below:

    class ObtainExperingAuthToken(ObtainAuthToken): def post(self, request, *args, **kargs): serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            print serializer
            user = UserProfile.objects.get(email=serializer.data['username'])
            token, created = Token.objects.get_or_create(user=user)
    
            utc_now = timezone.now()
            if not created and token.created < utc_now - datetime.timedelta(hours=24):
                token.delete()
                print serializer.data
                token = Token.objects.create(user=serializer.data['user'])
                token.created = datetime.datetime.utcnow()
                token.save()
    
            groups = [group.name for group in user.groups.all()]
            response_data = {
                'email': user.email,
                'token': token.key,
                'groups': groups
            }
    
            return HttpResponse(json.dumps(response_data), content_type='application/json')
        return HttpResponse(serializer.errors, status=400)
    

    @Edit The value for REST_FRAMEWORK

    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
        ],
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework.authentication.SessionAuthentication',
            'accounts.authentication.ExpiringTokenAuthentication',
        ],
        'DEFAULT_PARSER_CLASSES': [
            'rest_framework.parsers.JSONParser',
            'rest_framework.parsers.FormParser',
            'rest_framework.parsers.MultiPartParser',
            'rest_framework.parsers.FileUploadParser'
        ]
    }
    

    Firstly although it's not very clear from your explanation, but I'm guessing you are getting 400 error in the api responsible for providing user access token. Since obviously there would be no authentication on this api (except Client Authentication maybe), so you are genuinely getting bad request error since you are providing it with invalid data as you mentioned yourself. Authentication error comes when you access an api that doesn't allow unauthenticated access, which shouldn't be the case for the api that actually provides the authentication token.

    Secondly to get Authentication error you need to add Authentication Classes to either REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'] or to the AUTHENTICATION_CLASSES variable of the view class.

    链接地址: http://www.djcxy.com/p/33776.html

    上一篇: Django DRF令牌认证

    下一篇: Django Rest框架身份验证错误