Django OAuth Toolkit: Allow access token expiration date per user
In this tutorial, I will demonstrate how to implement a per-user access token expiration for Django OAuth Toolkit.
Setup OAuth Toolkit
Override OAUTH2_VALIDATOR_CLASS in settings.py
OAUTH2_PROVIDER = {
'ACCESS_TOKEN_EXPIRE_SECONDS': 1800, # 30 minutes
'REFRESH_TOKEN_EXPIRE_SECONDS': 3600, # 1 hour
'OAUTH2_VALIDATOR_CLASS': 'py_app.validator.MyOAuth2Validator',
}
Custom Validator
Create the custom validator
Create MyOAuth2Validator.py inside <app-root>/py_app/validator
*Create validator folder if it doesn't exist yet
Override save_bearer_token method to check for our custom expiration field and use it if there's any.
from oauth2_provider.oauth2_validators import OAuth2Validator
from oauth2_provider.models import AccessToken
class MyOAuth2Validator(OAuth2Validator):
""" Primarily extend the functionality of token generation """
def save_bearer_token(self, token, request, *args, **kwargs):
from datetime import datetime, timedelta
super(MyOAuth2Validator, self).save_bearer_token(token, request, *args, **kwargs)
ip = self.get_client_ip(request)
accessToken = AccessToken.objects.get(token=token.get('access_token'))
if accessToken.user.detail.session_expire_in is not None:
accessToken.expires = datetime.now() + timedelta(seconds=accessToken.user.detail.session_expire_in)
accessToken.save()
Custom field
We first need to create a model that we can link to our user model. We can call it UserDetail.
Create this class on a dedicated django app or on any existing app model.
class UserDetail(models.Model):
user = models.OneToOneField(USER_MODEL, related_name='detail', on_delete=models.CASCADE, null=True, blank=True)
session_expire_in = models.IntegerField(default=None, null=True, blank=True)
And that's it.. Run the makemigrations, migrate and runserver.
Have fun!