Django Rest Framework JWT - 具有扩展用户的自定义有效负载

时间:2017-10-30 05:10:35

标签: python django django-rest-framework django-rest-framework-jwt

我有一个带有示例序列化程序的扩展用户(配置文件是扩展用户,而不是抽象用户)

 {
    "id": 3,
    "url": "http://localhost:8000/api/v1/users/demo/",
    "username": "demo",
    "first_name": "First",
    "last_name": "Demo",
    "profile": {
        "gender": null,
        "location": "Sa Pa",
        "date_of_birth": null,
        "job_title": null,
        "phone_number": null,
        "fax_number": "",
        "website": "",
        "intro": "",
        "bio": "",
        "interested_in": null,
        "languages": null,
        "quotes": null,
        "nickname": null
    }
}

如何使用以上所有字段自定义有效负载并使用axios获取? 现在它只是获得有效载荷:

authUser:Object
email:"test@gmail.com"
exp:1509183691
user_id:1
username:"First Demo"
token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImxlY29uZ3RvYW4iLCJ1c2VyX2lkIjoxLCJlbWFpbCI6ImRyYWZ0bGlnb25ncXVhbjdAZ21haWwuY29tIiwiZXhwIjoxNTA5MTgzNjkxfQ.KSEp-7g-SGDbqfspedNwkT1rABFi0UQ45yKDJDTX2zA"

我关注此链接:#145但不起作用 请帮帮我!

1 个答案:

答案 0 :(得分:3)

这是我做的:

  • 创建自己的jwt_response_payload_handler

    from your_serializers import UserSerializer
    
    def jwt_response_payload_handler(token, user=None, request=None):
        return {
            'token': token,
            'user': UserSerializer(user, context={'request':request}).data
        }
    
  • 将自定义响应有效负载处理程序放入settings.py文件中:

    JWT_AUTH = {
        ...,                
        'JWT_RESPONSE_PAYLOAD_HANDLER': 'path_to.jwt_response_payload_handler',
        ...
    }
    

当您登录时,您会使用序列化数据返回tokenuser