欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自定义返回jwt验证数据

程序员文章站 2022-06-13 20:13:27
...

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. 需要修改一下源码
      自定义返回jwt验证数据
      自定义返回jwt验证数据
  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'
    

)
```

相关标签: jwt