【问题标题】:Manual token with Django Rest Framework JWT使用 Django Rest Framework JWT 的手动令牌
【发布时间】:2017-03-30 16:46:37
【问题描述】:

我目前正在使用 Django Rest Framework JWT 对项目进行身份验证。我已经实现了 BasicAuthentication、SessionAuthentication 和 JSONWebTokenAuthentication,用户可以通过对每个新会话使用 POST 方法来请求令牌。但是,我希望在创建每个用户后立即创建令牌(并且可能在管理部分中查看)。

我查看了 Django Rest Framework JWT 文档,其中指出可以使用以下方法手动创建令牌:

from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)

我尝试将此代码 sn-p 放在 views.py、models.py 和 serializers.py 中,但我不断收到关于“用户”的引用错误。

任何有关如何正确实现此代码 sn-p 或替代方法的帮助将不胜感激。谢谢

【问题讨论】:

    标签: python django django-rest-framework json-web-token django-rest-auth


    【解决方案1】:

    我没有按照官方文档中的示例进行操作。因为我得到了第二行和第三行的错误。我的配置在我的设置路径上引发了异常。

    我直接从库本身调用函数。

    from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler
    

    假设我的函数将 1 个字典作为输入并返回 token

    from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler
    
    def create_token(platform_data: typing.Dict):
        """
        System will search from userprofile model
        Then create user instance
        :param platform_data:
        :return:
        """
        # If found `userprofile `in the system use the existing
        # If not create new `user` and `userprofile`
    
        platform_id = platform_data.get('id')  # Can trust this because it is primary key
        email = platform_data.get('email')  # This is user input should not trust
    
        userprofile_qs = UserProfile.objects.filter(platform_id=platform_id)
        if userprofile_qs.exists():
            # user exists in the system
            # return Response token
            userprofile = userprofile_qs.first()
            user = userprofile.user
        else:
            # Create user and then bind it with userprofile
            user = User.objects.create(
                username=f'poink{platform_id}',
            )
        user.email = email  # Get latest email
        user.save()
        UserProfile.objects.create(
            platform_id=platform_id,
            user=user,
        )
    
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return token
    

    希望从中得到灵感

    【讨论】:

      猜你喜欢
      • 2019-08-01
      • 2017-06-25
      • 2019-06-20
      • 2019-02-26
      • 2020-06-18
      • 2017-05-28
      • 2016-08-24
      • 1970-01-01
      • 2018-02-24
      相关资源
      最近更新 更多