Django:将数据添加到JWT有效负载

2024-05-14 23:14:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想向由this library生成的JWT的有效负载中添加数据(例如令牌过期日期或用户信息)

此库生成的JWT的当前解码有效负载如下所示:

{
  "token": "sXF6EE6jlZRmKhx1mgodOCdUMuSE1I"
}

我想要这样的东西

{
  "expiration_date": 1588329561
}

我没有实现任何序列化程序或视图,因为库管理序列化程序和视图

我只需在urls.py文件中声明以下URL:

urlpatterns = [
    ...,
    path('auth/', include('drf_social_oauth2.urls', namespace='drf')),
    ...,
]

然后我可以发出POST请求来生成JWT或将JWT刷新到auth/token/

我见过(使用其他库的人)尝试修改库的解决方案,以及其他实现序列化程序和视图的解决方案,但由于我使用的库负责此任务,我不知道如何解决此问题

注:

  • drf-social-auth2的维护者表明它依赖于python-social-authdjango-oauth-toolkit

Tags: 数据用户程序tokenauth视图信息序列化
2条回答

我按照@omab的建议采取了以下方式:

步骤1)

在应用程序中创建一个文件(例如app/token_generator.py)并粘贴following function inside

步骤2)

将路径添加到settings.py中的令牌生成器

OAUTH2_PROVIDER = {
    'ACCESS_TOKEN_EXPIRE_SECONDS': 60 * 5,
    #this is my path, you should add yours
    'ACCESS_TOKEN_GENERATOR': 'user_auth.token_generator.token_generator'
}

示例(我的案例):

我想将到期日期添加到令牌负载中,因此我执行了以下操作:

try:
    from secrets import SystemRandom
except ImportError:
    from random import SystemRandom


UNICODE_ASCII_CHARACTER_SET = (
    'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789'
)


def token_generator(request, length=30, chars=UNICODE_ASCII_CHARACTER_SET):
    """Generates a non-guessable OAuth Json Web Token
    OAuth (1 and 2) does not specify the format of tokens except that they
    should be strings of random characters. Tokens should not be guessable
    and entropy when generating the random characters is important. Which is
    why SystemRandom is used instead of the default random.choice method.
    """
    from django.conf import settings
    from jose import jwt
    from datetime import datetime, timedelta
    import calendar

    rand = SystemRandom()
    secret = getattr(settings, 'SECRET_KEY')
    token = ''.join(rand.choice(chars) for x in range(length))

    expires_in = getattr(settings, 'OAUTH2_PROVIDER')['ACCESS_TOKEN_EXPIRE_SECONDS']
    exp = calendar.timegm((datetime.utcnow() + timedelta(seconds=expires_in)).utctimetuple())
    
    jwtted_token = jwt.encode({'token': token, 'exp': exp}, secret, algorithm='HS256')
    return jwtted_token

drf-social-oauth2没有提供一种机制来轻松覆盖此设置,它使用其generate_token方法(https://github.com/wagnerdelima/drf-social-oauth2/blob/master/drf_social_oauth2/settings.py#L11-L14)覆盖oauth2_provider.settings.ACCESS_TOKEN_GENERATOR,此方法不包括额外的值,只包括标记

您也可以使用添加所需键的自定义方法覆盖该值

相关问题 更多 >

    热门问题