自定义Django rest框架身份验证响应{“ detail”:“未提供身份验证凭据。”}

时间:2019-06-11 18:13:47

标签: python django django-rest-framework django-oauth

我正在使用django 2.1和python 3.6以及django rest框架3.8.2 ...我试图找到一种在身份验证失败时自定义json响应的方法。

我正在使用第三方软件包Django OAuth Toolkit

我唯一想到的方法是编写自定义身份验证类

{ "detail": "Authentication credentials were not provided." }
{ "Failure": "Authentication credentials were not provided. xyz etc" }

我试图覆盖BaseAuthorizationView

views.py

from django.http import HttpResponse
from oauth2_provider.views.base import TokenView, BaseAuthorizationView
from django.utils.decorators import method_decorator
from django.views.decorators.debug import sensitive_post_parameters
from oauth2_provider.models import get_access_token_model, get_application_model


class CustomAuthorizationView(BaseAuthorizationView):
    def dispatch(self, request, *args, **kwargs):
        self.oauth2_data = {}
        return super().dispatch(request, *args, **kwargs)

    def error_response(self, error, application, **kwargs):
        """
        Handle errors either by redirecting to redirect_uri with a json in the body containing
        error details or providing an error response
        """
        redirect, error_response = super().error_response(error, **kwargs)

        if redirect:
            return self.redirect(error_response["url"], application)

        status = error_response["error"].status_code
        return self.render_to_response("hello", status=status)

urls.py

urlpatterns = [
...
    url(r"o/authorize/", appointmentViews.CustomAuthorizationView, name="authorize"),
    path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
...

如果可以提供更多信息,请告诉我!预先谢谢你。

1 个答案:

答案 0 :(得分:0)

我最终用Django rest和自定义异常处理解决了我的问题 link

views.py

    def a():
        print ('a')
    def b():
        print('b')
    def c():
        print('c')
    def d():
        print('d')
    aa=[a(),b(),c(),d()]
    print(aa[1])

settings.py

from rest_framework.views import exception_handler


def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    if response is not None:
        response.data['status_code'] = response.status_code

    return response

where项目(文件夹)>应用程序(文件夹)> utils(文件夹)> exception.py>自定义...

响应:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'project.apps.utils.exception.custom_exception_handler'
}