authentik.providers.oauth2.token.base_fed
1from dataclasses import dataclass, field 2from typing import Any 3 4from django.db import IntegrityError 5from django.db.models import Q 6from django.http import HttpRequest 7from django.utils import timezone 8from jwt import PyJWT, PyJWTError, decode 9 10from authentik.core.models import ( 11 USER_ATTRIBUTE_EXPIRES, 12 USER_ATTRIBUTE_GENERATED, 13 USERNAME_MAX_LENGTH, 14 Actor, 15 Application, 16 User, 17 UserTypes, 18) 19from authentik.core.sources.mapper import SourceMapper 20from authentik.events.middleware import audit_ignore 21from authentik.lib.jwt_mldsa import key_from_jwk 22from authentik.providers.oauth2.errors import TokenError 23from authentik.providers.oauth2.models import ( 24 AccessToken, 25 OAuth2Provider, 26) 27from authentik.providers.oauth2.token.base import TokenRequest 28from authentik.providers.saml.models import SAMLProvider 29from authentik.sources.oauth.models import OAuthSource 30 31 32@dataclass(frozen=True) 33class FederatedParty: 34 """Details about a _verified_ federation party""" 35 36 parsed_token: dict[str, Any] 37 party: OAuth2Provider | OAuthSource 38 user: User | None = field(default=None) 39 40 @property 41 def type(self) -> str: 42 if isinstance(self.party, OAuth2Provider): 43 return "provider" 44 if isinstance(self.party, OAuthSource): 45 return "source" 46 raise ValueError(f"Invalid party type {self.party}") 47 48 49class FederatedTokenRequest(TokenRequest): 50 """Base class for token requests which involve federation, such as 51 client_credentials or token exchange""" 52 53 # Set by the grants that resolve an identity; read by check_policy_access and the 54 # response builders, so it must exist on every request type. 55 user: User | None = None 56 actor: Actor | None = None 57 # RFC 8693 ยง4.1 delegation chain carried by the subject_token's own `act` claim 58 prior_act: dict | None = None 59 requested_token_type: str | None = None 60 # Token exchange for a SAML Response: the SAML provider issuing it 61 saml_provider: SAMLProvider | None = None 62 63 def validate_jwt(self, assertion: str) -> FederatedParty | None: 64 if party := self.validate_jwt_from_source(assertion): 65 return party 66 elif party := self.validate_jwt_from_provider(assertion): 67 return party 68 return None 69 70 def validate_jwt_from_source(self, assertion: str) -> FederatedParty | None: 71 # Fully decode the JWT without verifying the signature, so we can get access to 72 # the header. 73 # Get the Key ID from the header, and use that to optimize our source query to only find 74 # sources that have a JWK for that Key ID 75 # The Key ID doesn't have a fixed format, but must match between an issued JWT 76 # and whatever is returned by the JWKS endpoint 77 try: 78 decode_unvalidated = PyJWT().decode_complete( 79 assertion, options={"verify_signature": False} 80 ) 81 except (PyJWTError, ValueError, TypeError, AttributeError) as exc: 82 self.logger.warning("failed to parse JWT for kid lookup", exc=exc) 83 raise TokenError("invalid_grant") from None 84 expected_kid = decode_unvalidated["header"].get("kid") 85 fallback_alg = decode_unvalidated["header"].get("alg") 86 if not expected_kid or not fallback_alg: 87 return None 88 for source in self.provider.jwt_federation_sources.filter( 89 oidc_jwks__keys__contains=[{"kid": expected_kid}] 90 ): 91 self.logger.debug("verifying JWT with source", source=source.slug) 92 keys = source.oidc_jwks.get("keys", []) 93 for key in keys: 94 if key.get("kid") and key.get("kid") != expected_kid: 95 continue 96 self.logger.debug("verifying JWT with key", source=source.slug, key=key.get("kid")) 97 try: 98 parsed_key, _ = key_from_jwk(key) 99 token = decode( 100 assertion, 101 parsed_key, 102 algorithms=[key.get("alg")] if "alg" in key else [fallback_alg], 103 options={ 104 "verify_aud": False, 105 }, 106 ) 107 # AttributeError is raised when the configured JWK is a private key 108 # and not a public key 109 except (PyJWTError, ValueError, TypeError, AttributeError) as exc: 110 self.logger.warning("failed to verify JWT", exc=exc, source=source.slug) 111 continue 112 # Return on the first key that verifies, so the source reported back is the 113 # one that actually validated the JWT rather than the last one iterated. 114 # The caller feeds this source into create_user_from_jwt, where it selects 115 # the user path and property mappings. 116 self.logger.info("successfully verified JWT with source", source=source.slug) 117 return FederatedParty(parsed_token=token, party=source) 118 return None 119 120 def validate_jwt_from_provider(self, assertion: str) -> FederatedParty | None: 121 token = provider = resolved_user = _key = None 122 providers = Q(provider__in=self.provider.jwt_federation_providers.all()) 123 if self.audience_provider or self.saml_provider: 124 # For token exchange with actor, the given token may likely be a token 125 # of the provider this request is for. A targeted provider has opted into 126 # the requesting provider, so its own tokens are accepted too. 127 providers |= Q(provider=self.provider) 128 federated_token = AccessToken.objects.filter(providers, token=assertion).first() 129 if federated_token: 130 _key, _alg = federated_token.provider.jwt_key 131 try: 132 verification_key = _key if isinstance(_key, str) else _key.public_key() 133 token = decode( 134 assertion, 135 verification_key, 136 algorithms=[_alg], 137 options={ 138 "verify_aud": False, 139 }, 140 ) 141 provider = federated_token.provider 142 resolved_user = federated_token.user 143 except (PyJWTError, ValueError, TypeError, AttributeError) as exc: 144 self.logger.warning( 145 "failed to verify JWT", exc=exc, provider=federated_token.provider.name 146 ) 147 148 if not token: 149 return None 150 self.logger.info("successfully verified JWT with provider", provider=provider.name) 151 return FederatedParty(parsed_token=token, party=provider, user=resolved_user) 152 153 def create_user_from_jwt( 154 self, party: FederatedParty, app: Application, request: HttpRequest 155 ) -> User: 156 """Create user from JWT""" 157 if not isinstance(party.party, OAuthSource): 158 raise ValueError("create_user_from_jwt can only be called with source as party") 159 with audit_ignore(): 160 # Run the JWT payload through the core mapping engine 161 mapped = SourceMapper(party.party).build_object_properties( 162 User, request=request, info=party.parsed_token, oauth_userinfo=party.parsed_token 163 ) 164 165 username = mapped.get( 166 "username", f"{self.provider.name}-{party.parsed_token.get('sub')}" 167 )[:USERNAME_MAX_LENGTH] 168 try: 169 user, created = User.objects.filter( 170 type=UserTypes.SERVICE_ACCOUNT, 171 **{f"attributes__{USER_ATTRIBUTE_GENERATED}": True}, 172 ).update_or_create( 173 username=username, 174 defaults={ 175 "last_login": timezone.now(), 176 "name": mapped.get( 177 "name", 178 f"Autogenerated user from application {app.name} " 179 "(client credentials JWT)", 180 ), 181 "email": mapped.get("email", ""), 182 "path": party.party.get_user_path(), 183 "type": UserTypes.SERVICE_ACCOUNT, 184 "attributes": mapped.get("attributes", {}) 185 | {USER_ATTRIBUTE_GENERATED: True}, 186 }, 187 ) 188 except IntegrityError: 189 self.logger.warning( 190 "User for JWT is not a generated service account", user=username 191 ) 192 raise TokenError("invalid_grant").with_cause("conflicting_user_exists") from None 193 user.attributes[USER_ATTRIBUTE_GENERATED] = True 194 user.save() 195 exp = party.parsed_token.get("exp") 196 if created and exp: 197 user.attributes[USER_ATTRIBUTE_EXPIRES] = exp 198 user.save() 199 return user
@dataclass(frozen=True)
class
FederatedParty:
33@dataclass(frozen=True) 34class FederatedParty: 35 """Details about a _verified_ federation party""" 36 37 parsed_token: dict[str, Any] 38 party: OAuth2Provider | OAuthSource 39 user: User | None = field(default=None) 40 41 @property 42 def type(self) -> str: 43 if isinstance(self.party, OAuth2Provider): 44 return "provider" 45 if isinstance(self.party, OAuthSource): 46 return "source" 47 raise ValueError(f"Invalid party type {self.party}")
Details about a _verified_ federation party
FederatedParty( parsed_token: dict[str, typing.Any], party: authentik.providers.oauth2.models.OAuth2Provider | authentik.sources.oauth.models.OAuthSource, user: authentik.core.models.User | None = None)
party: authentik.providers.oauth2.models.OAuth2Provider | authentik.sources.oauth.models.OAuthSource
50class FederatedTokenRequest(TokenRequest): 51 """Base class for token requests which involve federation, such as 52 client_credentials or token exchange""" 53 54 # Set by the grants that resolve an identity; read by check_policy_access and the 55 # response builders, so it must exist on every request type. 56 user: User | None = None 57 actor: Actor | None = None 58 # RFC 8693 ยง4.1 delegation chain carried by the subject_token's own `act` claim 59 prior_act: dict | None = None 60 requested_token_type: str | None = None 61 # Token exchange for a SAML Response: the SAML provider issuing it 62 saml_provider: SAMLProvider | None = None 63 64 def validate_jwt(self, assertion: str) -> FederatedParty | None: 65 if party := self.validate_jwt_from_source(assertion): 66 return party 67 elif party := self.validate_jwt_from_provider(assertion): 68 return party 69 return None 70 71 def validate_jwt_from_source(self, assertion: str) -> FederatedParty | None: 72 # Fully decode the JWT without verifying the signature, so we can get access to 73 # the header. 74 # Get the Key ID from the header, and use that to optimize our source query to only find 75 # sources that have a JWK for that Key ID 76 # The Key ID doesn't have a fixed format, but must match between an issued JWT 77 # and whatever is returned by the JWKS endpoint 78 try: 79 decode_unvalidated = PyJWT().decode_complete( 80 assertion, options={"verify_signature": False} 81 ) 82 except (PyJWTError, ValueError, TypeError, AttributeError) as exc: 83 self.logger.warning("failed to parse JWT for kid lookup", exc=exc) 84 raise TokenError("invalid_grant") from None 85 expected_kid = decode_unvalidated["header"].get("kid") 86 fallback_alg = decode_unvalidated["header"].get("alg") 87 if not expected_kid or not fallback_alg: 88 return None 89 for source in self.provider.jwt_federation_sources.filter( 90 oidc_jwks__keys__contains=[{"kid": expected_kid}] 91 ): 92 self.logger.debug("verifying JWT with source", source=source.slug) 93 keys = source.oidc_jwks.get("keys", []) 94 for key in keys: 95 if key.get("kid") and key.get("kid") != expected_kid: 96 continue 97 self.logger.debug("verifying JWT with key", source=source.slug, key=key.get("kid")) 98 try: 99 parsed_key, _ = key_from_jwk(key) 100 token = decode( 101 assertion, 102 parsed_key, 103 algorithms=[key.get("alg")] if "alg" in key else [fallback_alg], 104 options={ 105 "verify_aud": False, 106 }, 107 ) 108 # AttributeError is raised when the configured JWK is a private key 109 # and not a public key 110 except (PyJWTError, ValueError, TypeError, AttributeError) as exc: 111 self.logger.warning("failed to verify JWT", exc=exc, source=source.slug) 112 continue 113 # Return on the first key that verifies, so the source reported back is the 114 # one that actually validated the JWT rather than the last one iterated. 115 # The caller feeds this source into create_user_from_jwt, where it selects 116 # the user path and property mappings. 117 self.logger.info("successfully verified JWT with source", source=source.slug) 118 return FederatedParty(parsed_token=token, party=source) 119 return None 120 121 def validate_jwt_from_provider(self, assertion: str) -> FederatedParty | None: 122 token = provider = resolved_user = _key = None 123 providers = Q(provider__in=self.provider.jwt_federation_providers.all()) 124 if self.audience_provider or self.saml_provider: 125 # For token exchange with actor, the given token may likely be a token 126 # of the provider this request is for. A targeted provider has opted into 127 # the requesting provider, so its own tokens are accepted too. 128 providers |= Q(provider=self.provider) 129 federated_token = AccessToken.objects.filter(providers, token=assertion).first() 130 if federated_token: 131 _key, _alg = federated_token.provider.jwt_key 132 try: 133 verification_key = _key if isinstance(_key, str) else _key.public_key() 134 token = decode( 135 assertion, 136 verification_key, 137 algorithms=[_alg], 138 options={ 139 "verify_aud": False, 140 }, 141 ) 142 provider = federated_token.provider 143 resolved_user = federated_token.user 144 except (PyJWTError, ValueError, TypeError, AttributeError) as exc: 145 self.logger.warning( 146 "failed to verify JWT", exc=exc, provider=federated_token.provider.name 147 ) 148 149 if not token: 150 return None 151 self.logger.info("successfully verified JWT with provider", provider=provider.name) 152 return FederatedParty(parsed_token=token, party=provider, user=resolved_user) 153 154 def create_user_from_jwt( 155 self, party: FederatedParty, app: Application, request: HttpRequest 156 ) -> User: 157 """Create user from JWT""" 158 if not isinstance(party.party, OAuthSource): 159 raise ValueError("create_user_from_jwt can only be called with source as party") 160 with audit_ignore(): 161 # Run the JWT payload through the core mapping engine 162 mapped = SourceMapper(party.party).build_object_properties( 163 User, request=request, info=party.parsed_token, oauth_userinfo=party.parsed_token 164 ) 165 166 username = mapped.get( 167 "username", f"{self.provider.name}-{party.parsed_token.get('sub')}" 168 )[:USERNAME_MAX_LENGTH] 169 try: 170 user, created = User.objects.filter( 171 type=UserTypes.SERVICE_ACCOUNT, 172 **{f"attributes__{USER_ATTRIBUTE_GENERATED}": True}, 173 ).update_or_create( 174 username=username, 175 defaults={ 176 "last_login": timezone.now(), 177 "name": mapped.get( 178 "name", 179 f"Autogenerated user from application {app.name} " 180 "(client credentials JWT)", 181 ), 182 "email": mapped.get("email", ""), 183 "path": party.party.get_user_path(), 184 "type": UserTypes.SERVICE_ACCOUNT, 185 "attributes": mapped.get("attributes", {}) 186 | {USER_ATTRIBUTE_GENERATED: True}, 187 }, 188 ) 189 except IntegrityError: 190 self.logger.warning( 191 "User for JWT is not a generated service account", user=username 192 ) 193 raise TokenError("invalid_grant").with_cause("conflicting_user_exists") from None 194 user.attributes[USER_ATTRIBUTE_GENERATED] = True 195 user.save() 196 exp = party.parsed_token.get("exp") 197 if created and exp: 198 user.attributes[USER_ATTRIBUTE_EXPIRES] = exp 199 user.save() 200 return user
Base class for token requests which involve federation, such as client_credentials or token exchange
71 def validate_jwt_from_source(self, assertion: str) -> FederatedParty | None: 72 # Fully decode the JWT without verifying the signature, so we can get access to 73 # the header. 74 # Get the Key ID from the header, and use that to optimize our source query to only find 75 # sources that have a JWK for that Key ID 76 # The Key ID doesn't have a fixed format, but must match between an issued JWT 77 # and whatever is returned by the JWKS endpoint 78 try: 79 decode_unvalidated = PyJWT().decode_complete( 80 assertion, options={"verify_signature": False} 81 ) 82 except (PyJWTError, ValueError, TypeError, AttributeError) as exc: 83 self.logger.warning("failed to parse JWT for kid lookup", exc=exc) 84 raise TokenError("invalid_grant") from None 85 expected_kid = decode_unvalidated["header"].get("kid") 86 fallback_alg = decode_unvalidated["header"].get("alg") 87 if not expected_kid or not fallback_alg: 88 return None 89 for source in self.provider.jwt_federation_sources.filter( 90 oidc_jwks__keys__contains=[{"kid": expected_kid}] 91 ): 92 self.logger.debug("verifying JWT with source", source=source.slug) 93 keys = source.oidc_jwks.get("keys", []) 94 for key in keys: 95 if key.get("kid") and key.get("kid") != expected_kid: 96 continue 97 self.logger.debug("verifying JWT with key", source=source.slug, key=key.get("kid")) 98 try: 99 parsed_key, _ = key_from_jwk(key) 100 token = decode( 101 assertion, 102 parsed_key, 103 algorithms=[key.get("alg")] if "alg" in key else [fallback_alg], 104 options={ 105 "verify_aud": False, 106 }, 107 ) 108 # AttributeError is raised when the configured JWK is a private key 109 # and not a public key 110 except (PyJWTError, ValueError, TypeError, AttributeError) as exc: 111 self.logger.warning("failed to verify JWT", exc=exc, source=source.slug) 112 continue 113 # Return on the first key that verifies, so the source reported back is the 114 # one that actually validated the JWT rather than the last one iterated. 115 # The caller feeds this source into create_user_from_jwt, where it selects 116 # the user path and property mappings. 117 self.logger.info("successfully verified JWT with source", source=source.slug) 118 return FederatedParty(parsed_token=token, party=source) 119 return None
121 def validate_jwt_from_provider(self, assertion: str) -> FederatedParty | None: 122 token = provider = resolved_user = _key = None 123 providers = Q(provider__in=self.provider.jwt_federation_providers.all()) 124 if self.audience_provider or self.saml_provider: 125 # For token exchange with actor, the given token may likely be a token 126 # of the provider this request is for. A targeted provider has opted into 127 # the requesting provider, so its own tokens are accepted too. 128 providers |= Q(provider=self.provider) 129 federated_token = AccessToken.objects.filter(providers, token=assertion).first() 130 if federated_token: 131 _key, _alg = federated_token.provider.jwt_key 132 try: 133 verification_key = _key if isinstance(_key, str) else _key.public_key() 134 token = decode( 135 assertion, 136 verification_key, 137 algorithms=[_alg], 138 options={ 139 "verify_aud": False, 140 }, 141 ) 142 provider = federated_token.provider 143 resolved_user = federated_token.user 144 except (PyJWTError, ValueError, TypeError, AttributeError) as exc: 145 self.logger.warning( 146 "failed to verify JWT", exc=exc, provider=federated_token.provider.name 147 ) 148 149 if not token: 150 return None 151 self.logger.info("successfully verified JWT with provider", provider=provider.name) 152 return FederatedParty(parsed_token=token, party=provider, user=resolved_user)
def
create_user_from_jwt( self, party: FederatedParty, app: authentik.core.models.Application, request: django.http.request.HttpRequest) -> authentik.core.models.User:
154 def create_user_from_jwt( 155 self, party: FederatedParty, app: Application, request: HttpRequest 156 ) -> User: 157 """Create user from JWT""" 158 if not isinstance(party.party, OAuthSource): 159 raise ValueError("create_user_from_jwt can only be called with source as party") 160 with audit_ignore(): 161 # Run the JWT payload through the core mapping engine 162 mapped = SourceMapper(party.party).build_object_properties( 163 User, request=request, info=party.parsed_token, oauth_userinfo=party.parsed_token 164 ) 165 166 username = mapped.get( 167 "username", f"{self.provider.name}-{party.parsed_token.get('sub')}" 168 )[:USERNAME_MAX_LENGTH] 169 try: 170 user, created = User.objects.filter( 171 type=UserTypes.SERVICE_ACCOUNT, 172 **{f"attributes__{USER_ATTRIBUTE_GENERATED}": True}, 173 ).update_or_create( 174 username=username, 175 defaults={ 176 "last_login": timezone.now(), 177 "name": mapped.get( 178 "name", 179 f"Autogenerated user from application {app.name} " 180 "(client credentials JWT)", 181 ), 182 "email": mapped.get("email", ""), 183 "path": party.party.get_user_path(), 184 "type": UserTypes.SERVICE_ACCOUNT, 185 "attributes": mapped.get("attributes", {}) 186 | {USER_ATTRIBUTE_GENERATED: True}, 187 }, 188 ) 189 except IntegrityError: 190 self.logger.warning( 191 "User for JWT is not a generated service account", user=username 192 ) 193 raise TokenError("invalid_grant").with_cause("conflicting_user_exists") from None 194 user.attributes[USER_ATTRIBUTE_GENERATED] = True 195 user.save() 196 exp = party.parsed_token.get("exp") 197 if created and exp: 198 user.attributes[USER_ATTRIBUTE_EXPIRES] = exp 199 user.save() 200 return user
Create user from JWT