@@ -475,11 +475,15 @@ def save_bearer_token(self, token, request, *args, **kwargs):
475
475
if "scope" not in token :
476
476
raise FatalClientError ("Failed to renew access token: missing scope" )
477
477
478
+ # "authenticate_client" sets the client (Application) on request
479
+ application = request .client
480
+ access_token_expire_seconds = application .access_token_expire_seconds
481
+
478
482
# expires_in is passed to Server on initialization
479
483
# custom server class can have logic to override this
480
- expires = timezone . now () + timedelta ( seconds = token . get (
481
- "expires_in" , oauth2_settings . ACCESS_TOKEN_EXPIRE_SECONDS ,
482
- ))
484
+ expires = (
485
+ timezone . now () + timedelta ( seconds = access_token_expire_seconds )
486
+ )
483
487
484
488
if request .grant_type == "client_credentials" :
485
489
request .user = None
@@ -648,14 +652,38 @@ def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs
648
652
)
649
653
)
650
654
rt = RefreshToken .objects .filter (null_or_recent , token = refresh_token ).select_related (
651
- "access_token"
655
+ "access_token" ,
656
+ "application" ,
652
657
).first ()
653
658
654
659
if not rt :
655
660
return False
656
661
662
+ # Access and refresh token expiration is configurable by Application
663
+ # Determine refresh token expiration datetime by adding the timedelta
664
+ # of "refresh_token_expire_seconds" to the "created" datetime
665
+ expire_seconds = rt .application .refresh_token_expire_seconds
666
+ expires = rt .created + timedelta (seconds = expire_seconds )
667
+
668
+ is_expired = timezone .now () >= expires
669
+
670
+ # Revoke token if expired
671
+ if is_expired :
672
+ try :
673
+ rt .revoke ()
674
+ # Catch exception in case access or refresh token do not exist
675
+ except (AccessToken .DoesNotExist , RefreshToken .DoesNotExist ):
676
+ pass
677
+
657
678
request .user = rt .user
658
679
request .refresh_token = rt .token
659
680
# Temporary store RefreshToken instance to be reused by get_original_scopes and save_bearer_token.
660
681
request .refresh_token_instance = rt
661
- return rt .application == client
682
+
683
+ # Token is valid if it refers to the right client AND is not expired
684
+ is_valid = (
685
+ rt .application == client and
686
+ not is_expired
687
+ )
688
+
689
+ return is_valid
0 commit comments