【问题标题】:Store more than default information in django-rest-framework-jwt在 django-rest-framework-jwt 中存储超过默认信息
【发布时间】:2016-05-16 07:55:53
【问题描述】:

我正在使用 Django 1.8 版并使用 django-rest-framework-jwt 进行身份验证。 认证完成后,我们的应用程序会返回前端信息:

from rest_framework_jwt.settings import api_settings
from rest_framework.response import Response
from django.contrib.auth.models import User


jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

user.profile_picture = "test_profile_picture.jpg" #user is django.contrib.auth.models.User object
payload = jwt_payload_handler(user) 
token = jwt_encode_handler(payload)

 jwt_login_response = {
        "token": token
 }

return Response(jwt_login_response,status=status.HTTP_200_OK)

在前端,我们将通过解码

import jwtDecode from 'jwt-decode';
var decodedToken = jwtDecode(token);

但目前 decodedToken 仅包含 django-rest-framework-jwt 似乎默认的值

Object {username: "test", user_id: 9, email: "test@gmail.com", exp: 1454754137}

我想在 jwt 中存储更多信息,例如 profile_picture,但我不知道如何。我真的很想找到解决这个问题的方法。

【问题讨论】:

    标签: python django django-rest-framework jwt


    【解决方案1】:

    我认为您需要的是自定义用户模型。您可以通过使用所需字段创建新模型并通过一对一关系将其引用到默认用户模型来创建它。

    此链接可能会有所帮助 - http://blog.mathandpencil.com/replacing-django-custom-user-models-in-an-existing-application/

    【讨论】:

    • 我不认为他们的问题在于在 Python 中检索数据,他们显然有一种获取个人资料图片的方法。 JWT 数据也可以在 JS(或 JWT 客户端)中查看,这可能也是他们想要包含它的原因。
    【解决方案2】:

    您可以使用JWT_PAYLOAD_HANDLER setting 覆盖附加到令牌的有效负载。

    如您所见,默认实现包括usernameuser_idemailexp(到期时间)。你可以找到默认实现on GitHub

    【讨论】:

      猜你喜欢
      • 2016-08-24
      • 2016-06-10
      • 2021-03-10
      • 2020-08-09
      • 1970-01-01
      • 2018-03-03
      • 2019-05-12
      • 2019-08-01
      • 2019-06-25
      相关资源
      最近更新 更多