如何自定义Django rest框架中的[未提供身份验证凭据]错误消息

卡蒂克
  • 当我在邮递员中不传递标题时,DRF会给我此消息。

     {"detail": "Authentication credentials were not provided."}
    
  • 但是我想要一个类似以下的自定义消息。

       {
           "status": False,
           "message": "Authentication credentials were not provided.",
           "data": {}
       }
    
小伙子奥哈德

对于所有请求还是仅针对一个或两个API端点?

如果是针对某些api的操作,那么Arakkal Abu会在评论中链接您。我发现MyCustomExcpetion答案很好。

如果适用于所有端点,请使用这样的序列化器/中间件(JWT示例):

file: url.py
from rest_framework_jwt.views import ObtainJSONWebToken, refresh_jwt_token

url('auth/', ObtainJSONWebToken.as_view(
    serializer_class=CustomJWTSerializer)),


file: serializer.py

from rest_framework import serializers
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.utils import jwt_encode_handler, jwt_payload_handler

class CustomJWTSerializer(JSONWebTokenSerializer):
    
    def validate(self, attrs):
        credentials = {
                'email': attrs.get('email'),
                'password': attrs.get('password')
            }
        if all(credentials.values()):
            user = authenticate(**credentials)
            if user:
                payload = jwt_payload_handler(user)
                return {
                   'token': jwt_encode_handler(payload),
                   'user': user}
            else:
                return {msg: 'other error msg'}
        else:
            return {
             'status': False,
             'message': 'Authentication credentials were not provided.',
             'data': {}
                 }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何解决“详细信息”:“未提供身份验证凭据。” 基于类的 APIView Django REST 框架的错误?

未提供身份验证凭据django-rest-auth

Django Rest Framework-未提供身份验证凭据

Django Rest Framework JWT 未提供身份验证凭据

未提供 Django 身份验证凭据

django-oauth-toolkit; Django Rest Framework-未提供身份验证凭据

django rest 框架 ImageField 中的自定义验证错误消息

Django : "detail": "未提供身份验证凭据。"

Django身份验证自定义

Django Rest Framework自定义JWT身份验证

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

如何自定义Django Rest身份验证电子邮件上下文

如何自定义django rest身份验证密码重置电子邮件内容/模板

未调用自定义身份验证提供程序

创建Firebase身份验证的自定义错误消息

Django auth自定义业务逻辑-如何引发自定义错误消息?

Django REST Framework 中自定义身份验证的返回值

Django Rest Framework 中的 JWT 和自定义身份验证

Django Rest Framework自定义身份验证+基本身份验证

如何在Django中显示自定义错误?

如何在Django中显示自定义错误页面

Django Rest框架中的自定义403错误页面

如何自定义Django表单的提交和验证方法?

Django-如何使用自定义模型创建身份验证系统

如何制作自定义权限 django-rest

如何在Django-AllAuth中自定义ResetPasswordForm

如何在 django 中创建自定义 ID?

如何在 django adminlte 中添加自定义视图?

如何在Django中命名自定义表单的字段?