使用 Django Rest Framework JWT 的手动令牌

Posted

技术标签:

【中文标题】使用 Django Rest Framework JWT 的手动令牌【英文标题】:Manual token with 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 或替代方法的帮助将不胜感激。谢谢

【问题讨论】:

【参考方案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'poinkplatform_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

希望从中得到灵感

【讨论】:

以上是关于使用 Django Rest Framework JWT 的手动令牌的主要内容,如果未能解决你的问题,请参考以下文章

Django Rest Framework 和 django Rest Framework simplejwt 两因素身份验证

18-Django REST framework-使用Django开发REST 接口

如何在 django-rest-framework 中为 API 使用 TokenAuthentication

Django-rest-framework 和 django-rest-framework-jwt APIViews and validation Authorization headers

django rest framework中文介绍

使用 django-rest-framework-simplejwt 注册后返回令牌