简体   繁体   English

Django Rest - 如何在身份验证失败时返回自定义 json 响应?

[英]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.

相关问题 repoze.who身份验证失败时,如何返回JSON输出? - How can I return JSON output when repoze.who authentication fails? 如何在Django REST Framework中返回自定义JSON - How to return custom JSON in Django REST Framework 从 ListAPIView Django 3.0 Rest Framework 返回自定义 JSON 响应 - Return custom JSON response from ListAPIView Django 3.0 Rest Framework Django - 我如何返回 json 响应错误? - Django - how can i return a json response error? 如何在django rest框架中返回自定义词典作为“create”方法的响应? - How to return custom dictionary as response for a “create” method in django rest framework? Django rest 框架 - 自定义 Json 响应 - Django rest Framework - Custom Json Response 使用 Python Django 我怎么能做自定义 function,保存到数据库并返回 Z466DEEC716ECDF5FCA54D8 响应 - Using Python Django how could I do custom function, save to db and return json response 如何使用Django Rest Framework序列化器构建我的JSON响应? - How can I structure my JSON response using the Django Rest Framework serializer? 如何将Django REST Framework JSON响应的一部分从列表更改为字典? - How can I change part of a Django REST Framework JSON response from a list to a dictionary? 如何在 Django REST 框架 JSON:ZDB974238714CA8A1434A7CE1D08 响应中设置 ID - how I can set ID in Django REST Framework JSON:API response?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM