技术堆栈Django1.10.8 + Python3.6 + docker + React + Axios.js
我遇到一种情况,需要进行服务器到服务器的调用,为此,我正在使用Django-OAuth-toolkit。我该如何转换此令牌以发行JWT令牌?
{ “ access_token”:“ txxxxxxxxxxxxxxxxxxxxxFB45a”, “ expires_in”:36000, “ token_type”:“承载者”, “ scope”:“读写组”, “ refresh_token”:“ 16oKxxxxxxxxxxxxxxxxxxxxxxxx” }
到
{ “ access_token”:“ xxxxxxxx.xxxxxx.xxxxx”, “ expires_in”:36000, “ token_type”:“承载者”, “ scope”:“读写组”, “ refresh_token”:“ xxxxxxxx.xxxxxx.xxxxx” }
我经历了https://github.com/Humanitec/django-oauth-toolkit-jwt/ 但我认为django-oauth-toolkit使用的版本不兼容。
答案 0 :(得分:1)
我通过将oauthlib.oauth2.Server
子类化解决了它
class OauthServer(oauth2.Server):
def __init__(self, request_validator, token_expires_in=None, token_generator=None, *args, **kwargs):
token_generator = custom_token_generator
super().__init__(request_validator, token_expires_in, token_generator, *args, **kwargs)
custom_token_generator
函数将生成jwt令牌
def custom_token_generator(request, refresh_token=False):
client_code = request.user and request.user.client.codigo
now = datetime.now()
payload = {
'iat': int(now.timestamp()),
'exp': int(expires.timestamp()),
}
if client_code:
payload['org'] = client_code
return jwt.encode(payload, settings.JWT['EC_PRIVATE_KEY'].encode(), algorithm='ES256').decode('ascii')
这不是理想的JWT,但是您可以满足需要,唯一的问题是将AccessToken和RefreshToken token
字段更改为TextField,因为JWT的长度将超出限制
from oauth2_provider.models import AbstractAccessToken, AbstractRefreshToken
class AccessToken(AbstractAccessToken):
token = models.TextField()
class RefreshToken(AbstractRefreshToken):
token = models.TextField()
django-oauth-toolkit docs将提供有关在Django设置上覆盖这些字段的更多信息