authentik.providers.oauth2.token.refresh_token
1from datetime import datetime 2from typing import NoReturn 3 4from django.http import HttpRequest 5from django.utils import timezone 6 7from authentik.events.models import Event, EventAction 8from authentik.lib.utils.time import timedelta_from_string 9from authentik.providers.oauth2.errors import TokenError 10from authentik.providers.oauth2.models import RefreshToken 11from authentik.providers.oauth2.token.base import TokenRequest 12 13 14class RefreshTokenTokenRequest(TokenRequest): 15 16 refresh_token: RefreshToken | None = None 17 18 def parse(self, request: HttpRequest) -> None: 19 super().parse(request) 20 raw_token = request.POST.get("refresh_token", "") 21 if not raw_token: 22 self.logger.warning("Missing refresh token") 23 raise TokenError("invalid_grant") 24 25 self.refresh_token = RefreshToken.objects.filter( 26 RefreshToken.token_query(raw_token), provider=self.provider 27 ).first() 28 if not self.refresh_token: 29 self.logger.warning("Refresh token does not exist") 30 raise TokenError("invalid_grant") 31 if self.refresh_token.is_expired: 32 self.logger.warning("Refresh token is expired") 33 raise TokenError("invalid_grant") 34 if not self.refresh_token.user.is_active: 35 # A user's tokens are deleted when it is deactivated, but a refresh racing with that 36 # can issue tokens which the deletion doesn't see 37 self.logger.warning("Refresh token user is inactive") 38 raise TokenError("invalid_grant") 39 # https://datatracker.ietf.org/doc/html/rfc6749#section-6 40 # Fallback to original token's scopes when none are given 41 if not self.scope: 42 self.scope = self.refresh_token.scope 43 if self.refresh_token.dpop_jkt: 44 self.validate_dpop( 45 request, 46 self.refresh_token.dpop_jkt, 47 flow_name="refresh token", 48 ) 49 50 def claim(self, now: datetime, rotate: bool) -> bool: 51 """Decide whether this request may use the refresh token, and if `rotate` is set, 52 consume it so that a successor may be issued. Must be called in the same transaction 53 which issues the new tokens. 54 55 The token was loaded before its family was locked, so it is loaded again under the 56 lock (see `RefreshToken.lock_family`): a concurrent rotation or revocation of the family 57 has either committed and is seen here, or waits until the tokens issued by this request 58 are committed. Of several requests presenting the same active token, exactly one 59 consumes it, and the others are handled like reuse of a rotated token (which they 60 are).""" 61 token = self.refresh_token 62 try: 63 token.start_family() 64 if not token.family: 65 # Never treat the token as part of the tokens without a family 66 raise TokenError("invalid_grant") 67 RefreshToken.lock_family(token.family) 68 token.refresh_from_db(fields=["revoked", "rotated_at", "expires", "expiring"]) 69 if token.is_expired: 70 # Expired since it was loaded, e.g. while waiting for the lock. That's not reuse 71 self.logger.info("Refresh token expired during the request") 72 raise TokenError("invalid_grant") 73 if not token.revoked: 74 if not rotate: 75 # The token stays valid, there's nothing to consume 76 return True 77 # Rotated now rather than when the request started, so that waiting for the 78 # lock doesn't shorten the grace period 79 if token.consume(timezone.now()): 80 return True 81 # Changed by something which doesn't hold the family's lock 82 token.refresh_from_db(fields=["revoked", "rotated_at"]) 83 except RefreshToken.DoesNotExist: 84 # Deleted concurrently, e.g. revoked via RFC 7009, or its user was deactivated 85 self.logger.info("Refresh token was deleted") 86 raise TokenError("invalid_grant") from None 87 # Reuse of a rotated (or revoked) token 88 return self.claim_reuse_grace(now) 89 90 def claim_reuse_grace(self, now: datetime) -> bool: 91 """Allow a rotated token to be used again within the grace period, for clients which 92 retry or send concurrent refresh requests. Only when family revocation is enabled""" 93 if not self.provider.refresh_token_revoke_family_on_reuse: 94 return False 95 grace_period = timedelta_from_string(self.provider.refresh_token_reuse_grace_period) 96 if grace_period.total_seconds() <= 0: 97 return False 98 if not self.refresh_token.claim_reuse_grace(now - grace_period): 99 return False 100 self.logger.info("Rotated refresh token reused within grace period") 101 return True 102 103 def reject_reuse(self, request: HttpRequest) -> NoReturn: 104 """A revoked refresh token was used, outside the grace period. This indicates the token 105 may have been stolen, so revoke its family (if configured). 106 https://datatracker.ietf.org/doc/html/rfc9700#section-4.14.2""" 107 self.logger.warning("Refresh token is revoked") 108 revoke_family = self.provider.refresh_token_revoke_family_on_reuse 109 if revoke_family: 110 self.refresh_token.revoke_family() 111 Event.new( 112 action=EventAction.SUSPICIOUS_REQUEST, 113 message="Revoked refresh token was used", 114 token=self.refresh_token, 115 provider=self.refresh_token.provider, 116 family_revoked=revoke_family, 117 ).from_http(request, user=self.refresh_token.user) 118 raise TokenError("invalid_grant")
15class RefreshTokenTokenRequest(TokenRequest): 16 17 refresh_token: RefreshToken | None = None 18 19 def parse(self, request: HttpRequest) -> None: 20 super().parse(request) 21 raw_token = request.POST.get("refresh_token", "") 22 if not raw_token: 23 self.logger.warning("Missing refresh token") 24 raise TokenError("invalid_grant") 25 26 self.refresh_token = RefreshToken.objects.filter( 27 RefreshToken.token_query(raw_token), provider=self.provider 28 ).first() 29 if not self.refresh_token: 30 self.logger.warning("Refresh token does not exist") 31 raise TokenError("invalid_grant") 32 if self.refresh_token.is_expired: 33 self.logger.warning("Refresh token is expired") 34 raise TokenError("invalid_grant") 35 if not self.refresh_token.user.is_active: 36 # A user's tokens are deleted when it is deactivated, but a refresh racing with that 37 # can issue tokens which the deletion doesn't see 38 self.logger.warning("Refresh token user is inactive") 39 raise TokenError("invalid_grant") 40 # https://datatracker.ietf.org/doc/html/rfc6749#section-6 41 # Fallback to original token's scopes when none are given 42 if not self.scope: 43 self.scope = self.refresh_token.scope 44 if self.refresh_token.dpop_jkt: 45 self.validate_dpop( 46 request, 47 self.refresh_token.dpop_jkt, 48 flow_name="refresh token", 49 ) 50 51 def claim(self, now: datetime, rotate: bool) -> bool: 52 """Decide whether this request may use the refresh token, and if `rotate` is set, 53 consume it so that a successor may be issued. Must be called in the same transaction 54 which issues the new tokens. 55 56 The token was loaded before its family was locked, so it is loaded again under the 57 lock (see `RefreshToken.lock_family`): a concurrent rotation or revocation of the family 58 has either committed and is seen here, or waits until the tokens issued by this request 59 are committed. Of several requests presenting the same active token, exactly one 60 consumes it, and the others are handled like reuse of a rotated token (which they 61 are).""" 62 token = self.refresh_token 63 try: 64 token.start_family() 65 if not token.family: 66 # Never treat the token as part of the tokens without a family 67 raise TokenError("invalid_grant") 68 RefreshToken.lock_family(token.family) 69 token.refresh_from_db(fields=["revoked", "rotated_at", "expires", "expiring"]) 70 if token.is_expired: 71 # Expired since it was loaded, e.g. while waiting for the lock. That's not reuse 72 self.logger.info("Refresh token expired during the request") 73 raise TokenError("invalid_grant") 74 if not token.revoked: 75 if not rotate: 76 # The token stays valid, there's nothing to consume 77 return True 78 # Rotated now rather than when the request started, so that waiting for the 79 # lock doesn't shorten the grace period 80 if token.consume(timezone.now()): 81 return True 82 # Changed by something which doesn't hold the family's lock 83 token.refresh_from_db(fields=["revoked", "rotated_at"]) 84 except RefreshToken.DoesNotExist: 85 # Deleted concurrently, e.g. revoked via RFC 7009, or its user was deactivated 86 self.logger.info("Refresh token was deleted") 87 raise TokenError("invalid_grant") from None 88 # Reuse of a rotated (or revoked) token 89 return self.claim_reuse_grace(now) 90 91 def claim_reuse_grace(self, now: datetime) -> bool: 92 """Allow a rotated token to be used again within the grace period, for clients which 93 retry or send concurrent refresh requests. Only when family revocation is enabled""" 94 if not self.provider.refresh_token_revoke_family_on_reuse: 95 return False 96 grace_period = timedelta_from_string(self.provider.refresh_token_reuse_grace_period) 97 if grace_period.total_seconds() <= 0: 98 return False 99 if not self.refresh_token.claim_reuse_grace(now - grace_period): 100 return False 101 self.logger.info("Rotated refresh token reused within grace period") 102 return True 103 104 def reject_reuse(self, request: HttpRequest) -> NoReturn: 105 """A revoked refresh token was used, outside the grace period. This indicates the token 106 may have been stolen, so revoke its family (if configured). 107 https://datatracker.ietf.org/doc/html/rfc9700#section-4.14.2""" 108 self.logger.warning("Refresh token is revoked") 109 revoke_family = self.provider.refresh_token_revoke_family_on_reuse 110 if revoke_family: 111 self.refresh_token.revoke_family() 112 Event.new( 113 action=EventAction.SUSPICIOUS_REQUEST, 114 message="Revoked refresh token was used", 115 token=self.refresh_token, 116 provider=self.refresh_token.provider, 117 family_revoked=revoke_family, 118 ).from_http(request, user=self.refresh_token.user) 119 raise TokenError("invalid_grant")
19 def parse(self, request: HttpRequest) -> None: 20 super().parse(request) 21 raw_token = request.POST.get("refresh_token", "") 22 if not raw_token: 23 self.logger.warning("Missing refresh token") 24 raise TokenError("invalid_grant") 25 26 self.refresh_token = RefreshToken.objects.filter( 27 RefreshToken.token_query(raw_token), provider=self.provider 28 ).first() 29 if not self.refresh_token: 30 self.logger.warning("Refresh token does not exist") 31 raise TokenError("invalid_grant") 32 if self.refresh_token.is_expired: 33 self.logger.warning("Refresh token is expired") 34 raise TokenError("invalid_grant") 35 if not self.refresh_token.user.is_active: 36 # A user's tokens are deleted when it is deactivated, but a refresh racing with that 37 # can issue tokens which the deletion doesn't see 38 self.logger.warning("Refresh token user is inactive") 39 raise TokenError("invalid_grant") 40 # https://datatracker.ietf.org/doc/html/rfc6749#section-6 41 # Fallback to original token's scopes when none are given 42 if not self.scope: 43 self.scope = self.refresh_token.scope 44 if self.refresh_token.dpop_jkt: 45 self.validate_dpop( 46 request, 47 self.refresh_token.dpop_jkt, 48 flow_name="refresh token", 49 )
51 def claim(self, now: datetime, rotate: bool) -> bool: 52 """Decide whether this request may use the refresh token, and if `rotate` is set, 53 consume it so that a successor may be issued. Must be called in the same transaction 54 which issues the new tokens. 55 56 The token was loaded before its family was locked, so it is loaded again under the 57 lock (see `RefreshToken.lock_family`): a concurrent rotation or revocation of the family 58 has either committed and is seen here, or waits until the tokens issued by this request 59 are committed. Of several requests presenting the same active token, exactly one 60 consumes it, and the others are handled like reuse of a rotated token (which they 61 are).""" 62 token = self.refresh_token 63 try: 64 token.start_family() 65 if not token.family: 66 # Never treat the token as part of the tokens without a family 67 raise TokenError("invalid_grant") 68 RefreshToken.lock_family(token.family) 69 token.refresh_from_db(fields=["revoked", "rotated_at", "expires", "expiring"]) 70 if token.is_expired: 71 # Expired since it was loaded, e.g. while waiting for the lock. That's not reuse 72 self.logger.info("Refresh token expired during the request") 73 raise TokenError("invalid_grant") 74 if not token.revoked: 75 if not rotate: 76 # The token stays valid, there's nothing to consume 77 return True 78 # Rotated now rather than when the request started, so that waiting for the 79 # lock doesn't shorten the grace period 80 if token.consume(timezone.now()): 81 return True 82 # Changed by something which doesn't hold the family's lock 83 token.refresh_from_db(fields=["revoked", "rotated_at"]) 84 except RefreshToken.DoesNotExist: 85 # Deleted concurrently, e.g. revoked via RFC 7009, or its user was deactivated 86 self.logger.info("Refresh token was deleted") 87 raise TokenError("invalid_grant") from None 88 # Reuse of a rotated (or revoked) token 89 return self.claim_reuse_grace(now)
Decide whether this request may use the refresh token, and if rotate is set,
consume it so that a successor may be issued. Must be called in the same transaction
which issues the new tokens.
The token was loaded before its family was locked, so it is loaded again under the
lock (see RefreshToken.lock_family): a concurrent rotation or revocation of the family
has either committed and is seen here, or waits until the tokens issued by this request
are committed. Of several requests presenting the same active token, exactly one
consumes it, and the others are handled like reuse of a rotated token (which they
are).
91 def claim_reuse_grace(self, now: datetime) -> bool: 92 """Allow a rotated token to be used again within the grace period, for clients which 93 retry or send concurrent refresh requests. Only when family revocation is enabled""" 94 if not self.provider.refresh_token_revoke_family_on_reuse: 95 return False 96 grace_period = timedelta_from_string(self.provider.refresh_token_reuse_grace_period) 97 if grace_period.total_seconds() <= 0: 98 return False 99 if not self.refresh_token.claim_reuse_grace(now - grace_period): 100 return False 101 self.logger.info("Rotated refresh token reused within grace period") 102 return True
Allow a rotated token to be used again within the grace period, for clients which retry or send concurrent refresh requests. Only when family revocation is enabled
104 def reject_reuse(self, request: HttpRequest) -> NoReturn: 105 """A revoked refresh token was used, outside the grace period. This indicates the token 106 may have been stolen, so revoke its family (if configured). 107 https://datatracker.ietf.org/doc/html/rfc9700#section-4.14.2""" 108 self.logger.warning("Refresh token is revoked") 109 revoke_family = self.provider.refresh_token_revoke_family_on_reuse 110 if revoke_family: 111 self.refresh_token.revoke_family() 112 Event.new( 113 action=EventAction.SUSPICIOUS_REQUEST, 114 message="Revoked refresh token was used", 115 token=self.refresh_token, 116 provider=self.refresh_token.provider, 117 family_revoked=revoke_family, 118 ).from_http(request, user=self.refresh_token.user) 119 raise TokenError("invalid_grant")
A revoked refresh token was used, outside the grace period. This indicates the token may have been stolen, so revoke its family (if configured). https://datatracker.ietf.org/doc/html/rfc9700#section-4.14.2