首页 文章

使用Django Rest Framework JWT的手动令牌

提问于
浏览
1

我目前正在使用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)

我尝试将此代码段放在views.py,models.py和serializers.py中,但我一直在“用户”上收到引用错误 .

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

1 回答

  • 0

    我没有按照官方文档上的例子 . 因为我得到了第2和第3行的错误 . 我的配置在我的设置路径上引发了异常 .

    我直接从库本身调用该函数 .

    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
    

    希望从中得到这个想法

相关问题