[英]Django Rest - how can i return a custom json response when authentication fails?
I created a custom middleware to authenticate every get request to an API endpoint that i created.我创建了一个自定义中间件来验证对我创建的 API 端点的每个获取请求。 Here is my code:
这是我的代码:
class TokenMiddleware(AuthenticationMiddleware):
def process_request(self, request):
if request.user.is_authenticated:
return None
else:
try:
token = request.GET[TOKEN_QUERY_PUBLIC]
secret = request.GET[TOKEN_QUERY_SECRET]
except Exception as e:
# A token isn't included in the query params
raise ValidationError(detail=str(e))
user = auth.authenticate(request, token=token, secret=secret)
if user:
auth.login(request, user)
else:
return HttpResponse('Authentication failed', status=404)
Now, instead of raising exceptions or returning an HTTP response, i would like to return a JSON string instead, something like: {'error': 'authentication failed'}
.现在,我不想引发异常或返回 HTTP 响应,而是返回一个 JSON 字符串,例如:
{'error': 'authentication failed'}
。 I know how i would do that from a standard view, but in this case i need to do it from a middleware.我知道我会如何从标准视图中做到这一点,但在这种情况下,我需要从中间件中做到这一点。 How can i do it?
我该怎么做? Thanks in advance!
提前致谢!
You can use JsonResponse
:您可以使用
JsonResponse
:
from django.http import JsonResponse
def process_request(self, request):
...
return JsonResponse({'error': 'authentication failed'})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.