【问题标题】:django rest framework autorization returns wrong status codedjango rest 框架自动化返回错误的状态码
【发布时间】:2022-01-28 16:01:20
【问题描述】:

我是 django 的新手。我有一个项目,手机可以使用令牌与服务器进行交互。在 settings.py 我有:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'UPLOADED_FILES_USE_URL': False,

    'DEFAULT_PAGINATION_CLASS': None,
    'PAGE_SIZE': DEFAULT_PAGE_SIZE,  # For views using PageNumberPagination
}

但是当使用邮递员时,我发送了一个带有无效令牌的请求,而不是 401(未经授权),403(禁止)正在返回。有什么特别的方法可以解决这个问题吗?

tnx

【问题讨论】:

  • 至少显示视图
  • 似乎是 csrf 问题.. 尝试添加 csrf_exempt
  • 问题是我不知道它是如何工作的。没有为此指定视图,或者至少我找不到。 @Exprator
  • 他在问你正在使用的方法
  • 他要求出示你们各自的views.py

标签: python django rest django-rest-framework http-status-codes


【解决方案1】:

documentation所述:

将使用的响应类型取决于身份验证方案。尽管可以使用多种认证方案,但只能使用一种方案来确定响应的类型。在确定响应类型时使用视图上设置的第一个身份验证类。

SessionAuthentication添加此摘录

被拒绝权限的未经身份验证的响应将导致 HTTP 403 Forbidden 响应。

你有你的答案。

TokenAuthentication 移动为第一个DEFAULT_AUTHENTICATION_CLASSES 或记录当前行为。

【讨论】:

    【解决方案2】:

    您仍然可以定义一个自定义异常处理程序,当发生AuthenticationFailedNotAuthenticated 异常时将发送HTTP_401_UNAUTHORIZED 异常。

    Official documentation

    您可以这样做(来自 GitHub 问题上的 this answer):

    from rest_framework import exceptions
    from rest_framework import status
    from rest_framework.views import exception_handler
    
    
    def custom_exception_handler(exc, context):
        response = exception_handler(exc, context)
        if isinstance(exc, (exceptions.AuthenticationFailed, exceptions.NotAuthenticated)):
            response.status_code = status.HTTP_401_UNAUTHORIZED
        return response
    

    并在您的 REST_FRAMEWORK 设置中进行配置:

    REST_FRAMEWORK = {
        # ...
        'EXCEPTION_HANDLER': 'path.to.your.custom_exception_handler',
        # ...
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 2014-10-16
      相关资源
      最近更新 更多