我正在使用 django 2.1 和 python 3.6 和 django rest framework 3.8.2 ...我试图找到一种在身份验证失败时自定义 json 响应的方法。
我正在使用第三方包Django OAuth Toolkit
我能想到的唯一方法是编写一个自定义身份验证类
{ "detail": "Authentication credentials were not provided." }
{ "Failure": "Authentication credentials were not provided. xyz etc" }
我尝试覆盖 BaseAuthorizationView
视图.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)
网址.py
urlpatterns = [
...
url(r"o/authorize/", appointmentViews.CustomAuthorizationView, name="authorize"),
path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
...
如果我能提供更多信息,请告诉我!先感谢您。