我通过子类化解决了它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 和 RefreshTokentoken
字段更改为 TextField,因为 JWT 长度将超出限制
from oauth2_provider.models import AbstractAccessToken, AbstractRefreshToken
class AccessToken(AbstractAccessToken):
token = models.TextField()
class RefreshToken(AbstractRefreshToken):
token = models.TextField()
django-oauth-toolkit 文档将提供有关在 django 设置上覆盖这些字段的更多信息