Django:将数据添加到JWT负载中



我想将数据(如令牌到期日期或用户信息(添加到此库生成的JWT的有效负载中。

该库生成的JWT的当前解码有效载荷如下:

{
"token": "sXF6EE6jlZRmKhx1mgodOCdUMuSE1I"
}

我想要像一样的东西

{
"expiration_date": 1588329561
}

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

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

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

然后我可以进行POST请求以生成或刷新到CCD_ 2的JWT。

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

注:

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

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

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

我按照@omab的建议做了以下事情:

步骤1(

在应用程序中创建一个文件(例如app/token_generator.py(,并在其中粘贴以下函数。

步骤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

最新更新