简体   繁体   中英

django-oauth-toolkit to issue a JWT token

Tech Stack Django1.10.8 + Python3.6 + docker + React + Axios.js

I have a situation where I need to make a server to server call and for this I am using Django-OAuth-toolkit. How can I convert this token to issue JWT token instead?

{ "access_token": "txxxxxxxxxxxxxxxxxxxxxFB45a", "expires_in": 36000, "token_type": "Bearer", "scope": "read write groups", "refresh_token": "16oKxxxxxxxxxxxxxxxxxxxxx" }

to

{ "access_token": "xxxxxxxx.xxxxxx.xxxxx", "expires_in": 36000, "token_type": "Bearer", "scope": "read write groups", "refresh_token": "xxxxxxxx.xxxxxx.xxxxx" }

I have gone through https://github.com/Humanitec/django-oauth-toolkit-jwt/ but I think the version I am using of django-oauth-toolkit are incompatible.

I solved it by subclassing the 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)

The custom_token_generator function will generate the jwt token

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')

It's not the ideal JWT, but you can make what you need, the only problem is changing the AccessToken and RefreshToken token field to a TextField since the JWT length will go way over the limit

from oauth2_provider.models import AbstractAccessToken, AbstractRefreshToken

class AccessToken(AbstractAccessToken):
    token = models.TextField()

class RefreshToken(AbstractRefreshToken):
    token = models.TextField()

the django-oauth-toolkit docs will have more information on overwriting these fields on the django settings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM