自定义返回jwt验证数据

标签: jwt

jwt数据返回

  1. 验证成功时候:

    1. 创建有给utli文件,重写jwt_response_payload_handler方法
      	def jwt_response_payload_handler(token, user=None, request=None):
      	    return {
      	        'token': token,
      	        'id': user.id,
      	        'username': user.username,
      	    }
      
    2. 在setting里面进行配置:
      	JWT_AUTH= {
      	JWT_RESPONSE_PAYLOAD_HANDLER': 'drf.utils.jwt_response_payload_handler',
      	}
      
  2. 验证失败的时候

    1. 需要修改一下源码
      在这里插入图片描述
      在这里插入图片描述
  3. 创建一个**`custom_exception**文件

    from rest_framework.views import exception_handler
    from rest_framework.exceptions import ValidationError
    
    
    def custom_exception_handler(exc, context):
        response = exception_handler(exc, context)
    
        if isinstance(exc, ValidationError):
            response.data['code'] = response.status_code
            response.data['data'] = []
            if isinstance(response.data, dict):
                response.data['message'] = list(dict(response.data).values())[0][0]
    
                for key in dict(response.data).keys():
                    if key not in ['code', 'data', 'message']:
                        response.data.pop(key)
            else:
                response.data['message'] = '输入有误'
            return response
    
        if response is not None:
            response.data.clear()
            response.data['code'] = response.status_code
            response.data['data'] = []
    
            if response.status_code == 404:
                try:
                    response.data['message'] = response.data.pop('detail')
                    response.data['message'] = "未找到"
                except KeyError:
                    response.data['message'] = "未找到"
    
            if response.status_code == 400:
    
                response.data['message'] = '输入错误'
    
            elif response.status_code == 401:
                response.data['message'] = '未认证'
    
            elif response.status_code >= 500:
                response.data['message'] = "服务器错误"
    
            elif response.status_code == 403:
                response.data['message'] = "权限不允许"
    
            elif response.status_code == 405:
                response.data['message'] = '请求不允许'
            else:
                response.data['message'] = '未知错误'
        return response
    
  4. 在setting里面进行配置

    'EXCEPTION_HANDLER': (
        'app06.custom_exception.custom_exception_handler'
    

)
```

版权声明:本文为qq_33759361原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_33759361/article/details/105681366