authentik.providers.oauth2.token.token_exchange

  1from typing import Any
  2from uuid import UUID
  3
  4from django.db.models import Q
  5from django.http import HttpRequest
  6
  7from authentik.common.oauth.constants import (
  8    ACTOR_TOKEN_TYPES,
  9    TOKEN_EXCHANGE_TOKEN_TYPES,
 10    TOKEN_TYPE_URI_ACCESS_TOKEN,
 11    TOKEN_TYPE_URI_AUTHENTIK_TOKEN,
 12    TOKEN_TYPE_URI_SAML2,
 13)
 14from authentik.core.models import Actor, Application, Token, TokenIntents
 15from authentik.events.models import Event, EventAction
 16from authentik.flows.planner import PLAN_CONTEXT_APPLICATION
 17from authentik.providers.oauth2.errors import TokenExchangeError
 18from authentik.providers.oauth2.models import OAuth2Provider
 19from authentik.providers.oauth2.token.base_fed import FederatedTokenRequest
 20from authentik.providers.saml.models import SAMLProvider
 21from authentik.stages.password.stage import PLAN_CONTEXT_METHOD, PLAN_CONTEXT_METHOD_ARGS
 22
 23# Upper bound on nested `act` claims, so repeated exchanges can't grow tokens unbounded
 24MAX_ACT_DEPTH = 10
 25
 26
 27class TokenExchangeTokenRequest(FederatedTokenRequest):
 28
 29    def resolve_saml_audience(self, audiences: list[str]) -> None:
 30        """A SAML Response is requested for the SAML provider whose application's `slug` or
 31        `pbm_uuid` is the `audience`, which must federate with the requesting provider."""
 32        if len(audiences) != 1 or not audiences[0]:
 33            self.logger.warning("SAML token exchange requires exactly one audience")
 34            raise TokenExchangeError("invalid_target").with_cause("saml_audience_required")
 35        audience = audiences[0]
 36        query = Q(application__slug=audience)
 37        try:
 38            query |= Q(application__pbm_uuid=UUID(audience))
 39        except ValueError:
 40            # Audience is not a UUID; keep slug-only lookup.
 41            pass
 42        target = SAMLProvider.objects.filter(query).first()
 43        if not target:
 44            self.logger.warning("Audience does not match any provider", audience=audience)
 45            raise TokenExchangeError("invalid_target").with_cause("unknown_target")
 46        if not target.jwt_federation_providers.filter(pk=self.provider.pk).exists():
 47            self.logger.warning("Audience does not federate with the requesting provider")
 48            raise TokenExchangeError("invalid_target").with_cause("target_not_federated")
 49        self.saml_provider = target
 50
 51    def resolve_audience(self, request: HttpRequest) -> None:
 52        """RFC 8693 §2.1 `audience`: the provider the issued token is for, named by its
 53        `client_id` or by its application's `pbm_uuid`. Targets that cannot be honored are
 54        refused with invalid_target (§2.2.2) rather than ignored."""
 55        # RFC 8707 resource indicators are not implemented.
 56        if request.POST.getlist("resource"):
 57            self.logger.warning("Resource indicators are not supported")
 58            raise TokenExchangeError("invalid_target").with_cause("target_unsupported")
 59        audiences = request.POST.getlist("audience")
 60        if request.POST.get("requested_token_type") == TOKEN_TYPE_URI_SAML2:
 61            return self.resolve_saml_audience(audiences)
 62        if not audiences:
 63            return
 64        # Multi-provider tokens are not supported.
 65        if len(audiences) > 1:
 66            self.logger.warning("Multiple audiences are not supported")
 67            raise TokenExchangeError("invalid_target").with_cause("multiple_audiences")
 68        audience = audiences[0]
 69        target = OAuth2Provider.objects.filter(client_id=audience).first()
 70        if not target:
 71            try:
 72                pbm_uuid = UUID(audience)
 73            except ValueError:
 74                pbm_uuid = None
 75            if pbm_uuid:
 76                target = OAuth2Provider.objects.filter(application__pbm_uuid=pbm_uuid).first()
 77        if not target:
 78            self.logger.warning("Audience does not match any provider", audience=audience)
 79            raise TokenExchangeError("invalid_target").with_cause("unknown_target")
 80        # Targeting itself is the default behavior, nothing to switch to.
 81        if target.pk == self.provider.pk:
 82            return
 83        # The target must explicitly federate with the requesting provider.
 84        if not target.jwt_federation_providers.filter(pk=self.provider.pk).exists():
 85            self.logger.warning("Audience does not federate with the requesting provider")
 86            raise TokenExchangeError("invalid_target").with_cause("target_not_federated")
 87        self.audience_provider = target
 88
 89    def parse(self, request: HttpRequest) -> None:
 90        """See https://datatracker.ietf.org/doc/html/rfc8693#section-2.1"""
 91        super().parse(request)
 92        subject_token = request.POST.get("subject_token", "")
 93        subject_token_type = request.POST.get("subject_token_type", "")
 94        if not subject_token or not subject_token_type:
 95            self.logger.warning("Missing subject_token or subject_token_type")
 96            raise TokenExchangeError("invalid_request").with_cause("missing_subject_token")
 97        if subject_token_type not in TOKEN_EXCHANGE_TOKEN_TYPES:
 98            self.logger.warning("Unsupported subject token type", token_type=subject_token_type)
 99            raise TokenExchangeError("invalid_request").with_cause("unsupported_subject_token_type")
100        if self.requested_token_type is None:
101            self.requested_token_type = TOKEN_TYPE_URI_ACCESS_TOKEN
102        if (
103            self.requested_token_type not in TOKEN_EXCHANGE_TOKEN_TYPES
104            and self.requested_token_type != TOKEN_TYPE_URI_SAML2
105        ):
106            self.logger.warning(
107                "Unsupported requested token type", token_type=self.requested_token_type
108            )
109            raise TokenExchangeError("invalid_request").with_cause(
110                "unsupported_requested_token_type"
111            )
112
113        federated_party = self.validate_jwt(subject_token)
114
115        if not federated_party:
116            # Expiry is enforced by PyJWT during signature verification, so an expired
117            # subject token also lands here.
118            self.logger.warning("No subject token could be verified")
119            raise TokenExchangeError("invalid_grant").with_cause("subject_token_not_verified")
120
121        app = Application.objects.filter(provider=self.provider).first()
122        if not app or not app.provider:
123            self.logger.info("token_exchange grant for provider without application")
124            raise TokenExchangeError("invalid_grant").with_cause("provider_without_application")
125
126        if federated_party.user:
127            self.user = federated_party.user
128        self.check_policy_access(app, request, oauth_jwt=federated_party.parsed_token)
129        if not federated_party.user:
130            self.user = self.create_user_from_jwt(federated_party, app, request)
131
132        if self.audience_provider:
133            # An application is also required to give the issued token an `iss`
134            target_app = Application.objects.filter(provider=self.audience_provider).first()
135            if not target_app:
136                self.logger.info("Audience provider has no application")
137                raise TokenExchangeError("invalid_target").with_cause("target_without_application")
138            self.check_policy_access(target_app, request, oauth_jwt=federated_party.parsed_token)
139        if self.saml_provider:
140            self.check_policy_access(
141                self.saml_provider.application, request, oauth_jwt=federated_party.parsed_token
142            )
143
144        self.prior_act = self.validate_prior_act(federated_party.parsed_token.get("act"))
145        self.post_init_token_exchange_actor(request)
146
147        method_args = {
148            "jwt": federated_party.parsed_token,
149            "subject_token_type": subject_token_type,
150            "requested_token_type": self.requested_token_type,
151            federated_party.type: federated_party.party,
152        }
153        if self.audience_provider:
154            method_args["audience"] = self.audience_provider.client_id
155        if self.saml_provider:
156            method_args["audience"] = str(self.saml_provider.application.pbm_uuid)
157        # The validated delegation chain the subject token carried; the new actor (if any)
158        # is recorded as the event's user.
159        if self.prior_act:
160            method_args["act"] = self.prior_act
161        # A delegated exchange is performed by the actor, so attribute the event to it; the
162        # audit log then records it as an agent acting on behalf of the verified subject,
163        # matching how direct API calls by an actor are attributed.
164        Event.new(
165            action=EventAction.LOGIN,
166            **{
167                PLAN_CONTEXT_METHOD: "token_exchange",
168                PLAN_CONTEXT_METHOD_ARGS: method_args,
169                PLAN_CONTEXT_APPLICATION: app,
170            },
171        ).from_http(request, user=self.actor or self.user)
172
173    def validate_prior_act(self, act: Any, depth: int = 0) -> dict | None:
174        """RFC 8693 §4.1: validate the delegation chain the verified subject_token carries
175        in its `act` claim. Only `sub`, `iss` and a nested `act` are kept; other claims are
176        not meaningful for delegation (§4.1) and are dropped."""
177        if act is None:
178            return None
179        if depth >= MAX_ACT_DEPTH:
180            self.logger.warning("Subject token delegation chain is too deep")
181            raise TokenExchangeError("invalid_grant").with_cause("act_chain_too_deep")
182        if not isinstance(act, dict) or not isinstance(act.get("sub"), str):
183            self.logger.warning("Subject token has a malformed act claim")
184            raise TokenExchangeError("invalid_grant").with_cause("invalid_act_claim")
185        valid = {"sub": act["sub"]}
186        if "iss" in act:
187            if not isinstance(act["iss"], str):
188                self.logger.warning("Subject token has a malformed act claim")
189                raise TokenExchangeError("invalid_grant").with_cause("invalid_act_claim")
190            valid["iss"] = act["iss"]
191        if "act" in act:
192            valid["act"] = self.validate_prior_act(act["act"], depth + 1)
193        return valid
194
195    def post_init_token_exchange_actor(self, request: HttpRequest):
196        """RFC 8693 §4.1 delegation: validate an optional `actor_token`, identifying who
197        is actually exercising the resulting token (e.g. an Actor acting for the
198        verified subject_token's human).
199
200        Actors without an owner (`parent=None`) may only be used via a JWT actor_token.
201        Actors with an owner may be used via a JWT *or* an authentik built-in Token,
202        but only by the human that owns them (`actor.parent_id == self.user.pk`)."""
203        actor_token = request.POST.get("actor_token", "")
204        actor_token_type = request.POST.get("actor_token_type", "")
205        if not actor_token and not actor_token_type:
206            return
207        if not actor_token or not actor_token_type:
208            self.logger.warning("Missing actor_token or actor_token_type")
209            raise TokenExchangeError("invalid_request").with_cause("missing_actor_token")
210        if actor_token_type not in ACTOR_TOKEN_TYPES:
211            self.logger.warning("Unsupported actor token type", token_type=actor_token_type)
212            raise TokenExchangeError("invalid_request").with_cause("unsupported_actor_token_type")
213
214        if actor_token_type == TOKEN_TYPE_URI_AUTHENTIK_TOKEN:
215            # Built-in tokens: only valid for actors with an owner -- same lookup idiom as
216            # TokenAuthentication.auth_user_lookup (authentik/api/authentication.py).
217            # Token.objects excludes expired tokens by default (ExpiringManager).
218            key_token = Token.objects.filter(
219                key=actor_token, intent=TokenIntents.INTENT_API
220            ).first()
221            if not key_token:
222                self.logger.warning("Actor token not found")
223                raise TokenExchangeError("invalid_grant").with_cause("actor_token_not_verified")
224            # Actor.objects excludes expired actors by default (ExpiringManager), so an
225            # expired actor_token's user simply won't resolve here.
226            actor = Actor.objects.filter(pk=key_token.user_id).first()
227            if not actor or actor.parent_id != self.user.pk:
228                self.logger.warning("Actor is not controlled by the verified subject")
229                raise TokenExchangeError("invalid_grant").with_cause("actor_not_controlled")
230        else:
231            # TOKEN_TYPE_URI_JWT: verified via the same federation-provider trust used
232            # for subject_token.
233            # Only the provider-federation path applies -- Actors are authentik-internal
234            # service accounts, never externally-sourced identities, so the source/JWKS
235            # path (validate_jwt_from_source) does not apply here.
236            federated_party = self.validate_jwt_from_provider(actor_token)
237            if not federated_party:
238                self.logger.warning("Actor token not found")
239                raise TokenExchangeError("invalid_grant").with_cause("actor_token_not_verified")
240            actor = Actor.objects.filter(pk=federated_party.user.pk).first()
241            if not actor:
242                self.logger.warning("Actor is not controlled by the verified subject")
243                raise TokenExchangeError("invalid_grant").with_cause("actor_not_controlled")
244            # Ownerless actors (parent=None) are allowed via JWT with no ownership check;
245            # owned actors must still belong to the verified subject.
246            if actor.parent_id is not None and actor.parent_id != self.user.pk:
247                self.logger.warning("Actor is not controlled by the verified subject")
248                raise TokenExchangeError("invalid_grant").with_cause("actor_not_controlled")
249
250        self.actor = actor
MAX_ACT_DEPTH = 10
class TokenExchangeTokenRequest(authentik.providers.oauth2.token.base_fed.FederatedTokenRequest):
 28class TokenExchangeTokenRequest(FederatedTokenRequest):
 29
 30    def resolve_saml_audience(self, audiences: list[str]) -> None:
 31        """A SAML Response is requested for the SAML provider whose application's `slug` or
 32        `pbm_uuid` is the `audience`, which must federate with the requesting provider."""
 33        if len(audiences) != 1 or not audiences[0]:
 34            self.logger.warning("SAML token exchange requires exactly one audience")
 35            raise TokenExchangeError("invalid_target").with_cause("saml_audience_required")
 36        audience = audiences[0]
 37        query = Q(application__slug=audience)
 38        try:
 39            query |= Q(application__pbm_uuid=UUID(audience))
 40        except ValueError:
 41            # Audience is not a UUID; keep slug-only lookup.
 42            pass
 43        target = SAMLProvider.objects.filter(query).first()
 44        if not target:
 45            self.logger.warning("Audience does not match any provider", audience=audience)
 46            raise TokenExchangeError("invalid_target").with_cause("unknown_target")
 47        if not target.jwt_federation_providers.filter(pk=self.provider.pk).exists():
 48            self.logger.warning("Audience does not federate with the requesting provider")
 49            raise TokenExchangeError("invalid_target").with_cause("target_not_federated")
 50        self.saml_provider = target
 51
 52    def resolve_audience(self, request: HttpRequest) -> None:
 53        """RFC 8693 §2.1 `audience`: the provider the issued token is for, named by its
 54        `client_id` or by its application's `pbm_uuid`. Targets that cannot be honored are
 55        refused with invalid_target (§2.2.2) rather than ignored."""
 56        # RFC 8707 resource indicators are not implemented.
 57        if request.POST.getlist("resource"):
 58            self.logger.warning("Resource indicators are not supported")
 59            raise TokenExchangeError("invalid_target").with_cause("target_unsupported")
 60        audiences = request.POST.getlist("audience")
 61        if request.POST.get("requested_token_type") == TOKEN_TYPE_URI_SAML2:
 62            return self.resolve_saml_audience(audiences)
 63        if not audiences:
 64            return
 65        # Multi-provider tokens are not supported.
 66        if len(audiences) > 1:
 67            self.logger.warning("Multiple audiences are not supported")
 68            raise TokenExchangeError("invalid_target").with_cause("multiple_audiences")
 69        audience = audiences[0]
 70        target = OAuth2Provider.objects.filter(client_id=audience).first()
 71        if not target:
 72            try:
 73                pbm_uuid = UUID(audience)
 74            except ValueError:
 75                pbm_uuid = None
 76            if pbm_uuid:
 77                target = OAuth2Provider.objects.filter(application__pbm_uuid=pbm_uuid).first()
 78        if not target:
 79            self.logger.warning("Audience does not match any provider", audience=audience)
 80            raise TokenExchangeError("invalid_target").with_cause("unknown_target")
 81        # Targeting itself is the default behavior, nothing to switch to.
 82        if target.pk == self.provider.pk:
 83            return
 84        # The target must explicitly federate with the requesting provider.
 85        if not target.jwt_federation_providers.filter(pk=self.provider.pk).exists():
 86            self.logger.warning("Audience does not federate with the requesting provider")
 87            raise TokenExchangeError("invalid_target").with_cause("target_not_federated")
 88        self.audience_provider = target
 89
 90    def parse(self, request: HttpRequest) -> None:
 91        """See https://datatracker.ietf.org/doc/html/rfc8693#section-2.1"""
 92        super().parse(request)
 93        subject_token = request.POST.get("subject_token", "")
 94        subject_token_type = request.POST.get("subject_token_type", "")
 95        if not subject_token or not subject_token_type:
 96            self.logger.warning("Missing subject_token or subject_token_type")
 97            raise TokenExchangeError("invalid_request").with_cause("missing_subject_token")
 98        if subject_token_type not in TOKEN_EXCHANGE_TOKEN_TYPES:
 99            self.logger.warning("Unsupported subject token type", token_type=subject_token_type)
100            raise TokenExchangeError("invalid_request").with_cause("unsupported_subject_token_type")
101        if self.requested_token_type is None:
102            self.requested_token_type = TOKEN_TYPE_URI_ACCESS_TOKEN
103        if (
104            self.requested_token_type not in TOKEN_EXCHANGE_TOKEN_TYPES
105            and self.requested_token_type != TOKEN_TYPE_URI_SAML2
106        ):
107            self.logger.warning(
108                "Unsupported requested token type", token_type=self.requested_token_type
109            )
110            raise TokenExchangeError("invalid_request").with_cause(
111                "unsupported_requested_token_type"
112            )
113
114        federated_party = self.validate_jwt(subject_token)
115
116        if not federated_party:
117            # Expiry is enforced by PyJWT during signature verification, so an expired
118            # subject token also lands here.
119            self.logger.warning("No subject token could be verified")
120            raise TokenExchangeError("invalid_grant").with_cause("subject_token_not_verified")
121
122        app = Application.objects.filter(provider=self.provider).first()
123        if not app or not app.provider:
124            self.logger.info("token_exchange grant for provider without application")
125            raise TokenExchangeError("invalid_grant").with_cause("provider_without_application")
126
127        if federated_party.user:
128            self.user = federated_party.user
129        self.check_policy_access(app, request, oauth_jwt=federated_party.parsed_token)
130        if not federated_party.user:
131            self.user = self.create_user_from_jwt(federated_party, app, request)
132
133        if self.audience_provider:
134            # An application is also required to give the issued token an `iss`
135            target_app = Application.objects.filter(provider=self.audience_provider).first()
136            if not target_app:
137                self.logger.info("Audience provider has no application")
138                raise TokenExchangeError("invalid_target").with_cause("target_without_application")
139            self.check_policy_access(target_app, request, oauth_jwt=federated_party.parsed_token)
140        if self.saml_provider:
141            self.check_policy_access(
142                self.saml_provider.application, request, oauth_jwt=federated_party.parsed_token
143            )
144
145        self.prior_act = self.validate_prior_act(federated_party.parsed_token.get("act"))
146        self.post_init_token_exchange_actor(request)
147
148        method_args = {
149            "jwt": federated_party.parsed_token,
150            "subject_token_type": subject_token_type,
151            "requested_token_type": self.requested_token_type,
152            federated_party.type: federated_party.party,
153        }
154        if self.audience_provider:
155            method_args["audience"] = self.audience_provider.client_id
156        if self.saml_provider:
157            method_args["audience"] = str(self.saml_provider.application.pbm_uuid)
158        # The validated delegation chain the subject token carried; the new actor (if any)
159        # is recorded as the event's user.
160        if self.prior_act:
161            method_args["act"] = self.prior_act
162        # A delegated exchange is performed by the actor, so attribute the event to it; the
163        # audit log then records it as an agent acting on behalf of the verified subject,
164        # matching how direct API calls by an actor are attributed.
165        Event.new(
166            action=EventAction.LOGIN,
167            **{
168                PLAN_CONTEXT_METHOD: "token_exchange",
169                PLAN_CONTEXT_METHOD_ARGS: method_args,
170                PLAN_CONTEXT_APPLICATION: app,
171            },
172        ).from_http(request, user=self.actor or self.user)
173
174    def validate_prior_act(self, act: Any, depth: int = 0) -> dict | None:
175        """RFC 8693 §4.1: validate the delegation chain the verified subject_token carries
176        in its `act` claim. Only `sub`, `iss` and a nested `act` are kept; other claims are
177        not meaningful for delegation (§4.1) and are dropped."""
178        if act is None:
179            return None
180        if depth >= MAX_ACT_DEPTH:
181            self.logger.warning("Subject token delegation chain is too deep")
182            raise TokenExchangeError("invalid_grant").with_cause("act_chain_too_deep")
183        if not isinstance(act, dict) or not isinstance(act.get("sub"), str):
184            self.logger.warning("Subject token has a malformed act claim")
185            raise TokenExchangeError("invalid_grant").with_cause("invalid_act_claim")
186        valid = {"sub": act["sub"]}
187        if "iss" in act:
188            if not isinstance(act["iss"], str):
189                self.logger.warning("Subject token has a malformed act claim")
190                raise TokenExchangeError("invalid_grant").with_cause("invalid_act_claim")
191            valid["iss"] = act["iss"]
192        if "act" in act:
193            valid["act"] = self.validate_prior_act(act["act"], depth + 1)
194        return valid
195
196    def post_init_token_exchange_actor(self, request: HttpRequest):
197        """RFC 8693 §4.1 delegation: validate an optional `actor_token`, identifying who
198        is actually exercising the resulting token (e.g. an Actor acting for the
199        verified subject_token's human).
200
201        Actors without an owner (`parent=None`) may only be used via a JWT actor_token.
202        Actors with an owner may be used via a JWT *or* an authentik built-in Token,
203        but only by the human that owns them (`actor.parent_id == self.user.pk`)."""
204        actor_token = request.POST.get("actor_token", "")
205        actor_token_type = request.POST.get("actor_token_type", "")
206        if not actor_token and not actor_token_type:
207            return
208        if not actor_token or not actor_token_type:
209            self.logger.warning("Missing actor_token or actor_token_type")
210            raise TokenExchangeError("invalid_request").with_cause("missing_actor_token")
211        if actor_token_type not in ACTOR_TOKEN_TYPES:
212            self.logger.warning("Unsupported actor token type", token_type=actor_token_type)
213            raise TokenExchangeError("invalid_request").with_cause("unsupported_actor_token_type")
214
215        if actor_token_type == TOKEN_TYPE_URI_AUTHENTIK_TOKEN:
216            # Built-in tokens: only valid for actors with an owner -- same lookup idiom as
217            # TokenAuthentication.auth_user_lookup (authentik/api/authentication.py).
218            # Token.objects excludes expired tokens by default (ExpiringManager).
219            key_token = Token.objects.filter(
220                key=actor_token, intent=TokenIntents.INTENT_API
221            ).first()
222            if not key_token:
223                self.logger.warning("Actor token not found")
224                raise TokenExchangeError("invalid_grant").with_cause("actor_token_not_verified")
225            # Actor.objects excludes expired actors by default (ExpiringManager), so an
226            # expired actor_token's user simply won't resolve here.
227            actor = Actor.objects.filter(pk=key_token.user_id).first()
228            if not actor or actor.parent_id != self.user.pk:
229                self.logger.warning("Actor is not controlled by the verified subject")
230                raise TokenExchangeError("invalid_grant").with_cause("actor_not_controlled")
231        else:
232            # TOKEN_TYPE_URI_JWT: verified via the same federation-provider trust used
233            # for subject_token.
234            # Only the provider-federation path applies -- Actors are authentik-internal
235            # service accounts, never externally-sourced identities, so the source/JWKS
236            # path (validate_jwt_from_source) does not apply here.
237            federated_party = self.validate_jwt_from_provider(actor_token)
238            if not federated_party:
239                self.logger.warning("Actor token not found")
240                raise TokenExchangeError("invalid_grant").with_cause("actor_token_not_verified")
241            actor = Actor.objects.filter(pk=federated_party.user.pk).first()
242            if not actor:
243                self.logger.warning("Actor is not controlled by the verified subject")
244                raise TokenExchangeError("invalid_grant").with_cause("actor_not_controlled")
245            # Ownerless actors (parent=None) are allowed via JWT with no ownership check;
246            # owned actors must still belong to the verified subject.
247            if actor.parent_id is not None and actor.parent_id != self.user.pk:
248                self.logger.warning("Actor is not controlled by the verified subject")
249                raise TokenExchangeError("invalid_grant").with_cause("actor_not_controlled")
250
251        self.actor = actor

Base class for token requests which involve federation, such as client_credentials or token exchange

def resolve_saml_audience(self, audiences: list[str]) -> None:
30    def resolve_saml_audience(self, audiences: list[str]) -> None:
31        """A SAML Response is requested for the SAML provider whose application's `slug` or
32        `pbm_uuid` is the `audience`, which must federate with the requesting provider."""
33        if len(audiences) != 1 or not audiences[0]:
34            self.logger.warning("SAML token exchange requires exactly one audience")
35            raise TokenExchangeError("invalid_target").with_cause("saml_audience_required")
36        audience = audiences[0]
37        query = Q(application__slug=audience)
38        try:
39            query |= Q(application__pbm_uuid=UUID(audience))
40        except ValueError:
41            # Audience is not a UUID; keep slug-only lookup.
42            pass
43        target = SAMLProvider.objects.filter(query).first()
44        if not target:
45            self.logger.warning("Audience does not match any provider", audience=audience)
46            raise TokenExchangeError("invalid_target").with_cause("unknown_target")
47        if not target.jwt_federation_providers.filter(pk=self.provider.pk).exists():
48            self.logger.warning("Audience does not federate with the requesting provider")
49            raise TokenExchangeError("invalid_target").with_cause("target_not_federated")
50        self.saml_provider = target

A SAML Response is requested for the SAML provider whose application's slug or pbm_uuid is the audience, which must federate with the requesting provider.

def resolve_audience(self, request: django.http.request.HttpRequest) -> None:
52    def resolve_audience(self, request: HttpRequest) -> None:
53        """RFC 8693 §2.1 `audience`: the provider the issued token is for, named by its
54        `client_id` or by its application's `pbm_uuid`. Targets that cannot be honored are
55        refused with invalid_target (§2.2.2) rather than ignored."""
56        # RFC 8707 resource indicators are not implemented.
57        if request.POST.getlist("resource"):
58            self.logger.warning("Resource indicators are not supported")
59            raise TokenExchangeError("invalid_target").with_cause("target_unsupported")
60        audiences = request.POST.getlist("audience")
61        if request.POST.get("requested_token_type") == TOKEN_TYPE_URI_SAML2:
62            return self.resolve_saml_audience(audiences)
63        if not audiences:
64            return
65        # Multi-provider tokens are not supported.
66        if len(audiences) > 1:
67            self.logger.warning("Multiple audiences are not supported")
68            raise TokenExchangeError("invalid_target").with_cause("multiple_audiences")
69        audience = audiences[0]
70        target = OAuth2Provider.objects.filter(client_id=audience).first()
71        if not target:
72            try:
73                pbm_uuid = UUID(audience)
74            except ValueError:
75                pbm_uuid = None
76            if pbm_uuid:
77                target = OAuth2Provider.objects.filter(application__pbm_uuid=pbm_uuid).first()
78        if not target:
79            self.logger.warning("Audience does not match any provider", audience=audience)
80            raise TokenExchangeError("invalid_target").with_cause("unknown_target")
81        # Targeting itself is the default behavior, nothing to switch to.
82        if target.pk == self.provider.pk:
83            return
84        # The target must explicitly federate with the requesting provider.
85        if not target.jwt_federation_providers.filter(pk=self.provider.pk).exists():
86            self.logger.warning("Audience does not federate with the requesting provider")
87            raise TokenExchangeError("invalid_target").with_cause("target_not_federated")
88        self.audience_provider = target

RFC 8693 §2.1 audience: the provider the issued token is for, named by its client_id or by its application's pbm_uuid. Targets that cannot be honored are refused with invalid_target (§2.2.2) rather than ignored.

def parse(self, request: django.http.request.HttpRequest) -> None:
 90    def parse(self, request: HttpRequest) -> None:
 91        """See https://datatracker.ietf.org/doc/html/rfc8693#section-2.1"""
 92        super().parse(request)
 93        subject_token = request.POST.get("subject_token", "")
 94        subject_token_type = request.POST.get("subject_token_type", "")
 95        if not subject_token or not subject_token_type:
 96            self.logger.warning("Missing subject_token or subject_token_type")
 97            raise TokenExchangeError("invalid_request").with_cause("missing_subject_token")
 98        if subject_token_type not in TOKEN_EXCHANGE_TOKEN_TYPES:
 99            self.logger.warning("Unsupported subject token type", token_type=subject_token_type)
100            raise TokenExchangeError("invalid_request").with_cause("unsupported_subject_token_type")
101        if self.requested_token_type is None:
102            self.requested_token_type = TOKEN_TYPE_URI_ACCESS_TOKEN
103        if (
104            self.requested_token_type not in TOKEN_EXCHANGE_TOKEN_TYPES
105            and self.requested_token_type != TOKEN_TYPE_URI_SAML2
106        ):
107            self.logger.warning(
108                "Unsupported requested token type", token_type=self.requested_token_type
109            )
110            raise TokenExchangeError("invalid_request").with_cause(
111                "unsupported_requested_token_type"
112            )
113
114        federated_party = self.validate_jwt(subject_token)
115
116        if not federated_party:
117            # Expiry is enforced by PyJWT during signature verification, so an expired
118            # subject token also lands here.
119            self.logger.warning("No subject token could be verified")
120            raise TokenExchangeError("invalid_grant").with_cause("subject_token_not_verified")
121
122        app = Application.objects.filter(provider=self.provider).first()
123        if not app or not app.provider:
124            self.logger.info("token_exchange grant for provider without application")
125            raise TokenExchangeError("invalid_grant").with_cause("provider_without_application")
126
127        if federated_party.user:
128            self.user = federated_party.user
129        self.check_policy_access(app, request, oauth_jwt=federated_party.parsed_token)
130        if not federated_party.user:
131            self.user = self.create_user_from_jwt(federated_party, app, request)
132
133        if self.audience_provider:
134            # An application is also required to give the issued token an `iss`
135            target_app = Application.objects.filter(provider=self.audience_provider).first()
136            if not target_app:
137                self.logger.info("Audience provider has no application")
138                raise TokenExchangeError("invalid_target").with_cause("target_without_application")
139            self.check_policy_access(target_app, request, oauth_jwt=federated_party.parsed_token)
140        if self.saml_provider:
141            self.check_policy_access(
142                self.saml_provider.application, request, oauth_jwt=federated_party.parsed_token
143            )
144
145        self.prior_act = self.validate_prior_act(federated_party.parsed_token.get("act"))
146        self.post_init_token_exchange_actor(request)
147
148        method_args = {
149            "jwt": federated_party.parsed_token,
150            "subject_token_type": subject_token_type,
151            "requested_token_type": self.requested_token_type,
152            federated_party.type: federated_party.party,
153        }
154        if self.audience_provider:
155            method_args["audience"] = self.audience_provider.client_id
156        if self.saml_provider:
157            method_args["audience"] = str(self.saml_provider.application.pbm_uuid)
158        # The validated delegation chain the subject token carried; the new actor (if any)
159        # is recorded as the event's user.
160        if self.prior_act:
161            method_args["act"] = self.prior_act
162        # A delegated exchange is performed by the actor, so attribute the event to it; the
163        # audit log then records it as an agent acting on behalf of the verified subject,
164        # matching how direct API calls by an actor are attributed.
165        Event.new(
166            action=EventAction.LOGIN,
167            **{
168                PLAN_CONTEXT_METHOD: "token_exchange",
169                PLAN_CONTEXT_METHOD_ARGS: method_args,
170                PLAN_CONTEXT_APPLICATION: app,
171            },
172        ).from_http(request, user=self.actor or self.user)
def validate_prior_act(self, act: Any, depth: int = 0) -> dict | None:
174    def validate_prior_act(self, act: Any, depth: int = 0) -> dict | None:
175        """RFC 8693 §4.1: validate the delegation chain the verified subject_token carries
176        in its `act` claim. Only `sub`, `iss` and a nested `act` are kept; other claims are
177        not meaningful for delegation (§4.1) and are dropped."""
178        if act is None:
179            return None
180        if depth >= MAX_ACT_DEPTH:
181            self.logger.warning("Subject token delegation chain is too deep")
182            raise TokenExchangeError("invalid_grant").with_cause("act_chain_too_deep")
183        if not isinstance(act, dict) or not isinstance(act.get("sub"), str):
184            self.logger.warning("Subject token has a malformed act claim")
185            raise TokenExchangeError("invalid_grant").with_cause("invalid_act_claim")
186        valid = {"sub": act["sub"]}
187        if "iss" in act:
188            if not isinstance(act["iss"], str):
189                self.logger.warning("Subject token has a malformed act claim")
190                raise TokenExchangeError("invalid_grant").with_cause("invalid_act_claim")
191            valid["iss"] = act["iss"]
192        if "act" in act:
193            valid["act"] = self.validate_prior_act(act["act"], depth + 1)
194        return valid

RFC 8693 §4.1: validate the delegation chain the verified subject_token carries in its act claim. Only sub, iss and a nested act are kept; other claims are not meaningful for delegation (§4.1) and are dropped.

def post_init_token_exchange_actor(self, request: django.http.request.HttpRequest):
196    def post_init_token_exchange_actor(self, request: HttpRequest):
197        """RFC 8693 §4.1 delegation: validate an optional `actor_token`, identifying who
198        is actually exercising the resulting token (e.g. an Actor acting for the
199        verified subject_token's human).
200
201        Actors without an owner (`parent=None`) may only be used via a JWT actor_token.
202        Actors with an owner may be used via a JWT *or* an authentik built-in Token,
203        but only by the human that owns them (`actor.parent_id == self.user.pk`)."""
204        actor_token = request.POST.get("actor_token", "")
205        actor_token_type = request.POST.get("actor_token_type", "")
206        if not actor_token and not actor_token_type:
207            return
208        if not actor_token or not actor_token_type:
209            self.logger.warning("Missing actor_token or actor_token_type")
210            raise TokenExchangeError("invalid_request").with_cause("missing_actor_token")
211        if actor_token_type not in ACTOR_TOKEN_TYPES:
212            self.logger.warning("Unsupported actor token type", token_type=actor_token_type)
213            raise TokenExchangeError("invalid_request").with_cause("unsupported_actor_token_type")
214
215        if actor_token_type == TOKEN_TYPE_URI_AUTHENTIK_TOKEN:
216            # Built-in tokens: only valid for actors with an owner -- same lookup idiom as
217            # TokenAuthentication.auth_user_lookup (authentik/api/authentication.py).
218            # Token.objects excludes expired tokens by default (ExpiringManager).
219            key_token = Token.objects.filter(
220                key=actor_token, intent=TokenIntents.INTENT_API
221            ).first()
222            if not key_token:
223                self.logger.warning("Actor token not found")
224                raise TokenExchangeError("invalid_grant").with_cause("actor_token_not_verified")
225            # Actor.objects excludes expired actors by default (ExpiringManager), so an
226            # expired actor_token's user simply won't resolve here.
227            actor = Actor.objects.filter(pk=key_token.user_id).first()
228            if not actor or actor.parent_id != self.user.pk:
229                self.logger.warning("Actor is not controlled by the verified subject")
230                raise TokenExchangeError("invalid_grant").with_cause("actor_not_controlled")
231        else:
232            # TOKEN_TYPE_URI_JWT: verified via the same federation-provider trust used
233            # for subject_token.
234            # Only the provider-federation path applies -- Actors are authentik-internal
235            # service accounts, never externally-sourced identities, so the source/JWKS
236            # path (validate_jwt_from_source) does not apply here.
237            federated_party = self.validate_jwt_from_provider(actor_token)
238            if not federated_party:
239                self.logger.warning("Actor token not found")
240                raise TokenExchangeError("invalid_grant").with_cause("actor_token_not_verified")
241            actor = Actor.objects.filter(pk=federated_party.user.pk).first()
242            if not actor:
243                self.logger.warning("Actor is not controlled by the verified subject")
244                raise TokenExchangeError("invalid_grant").with_cause("actor_not_controlled")
245            # Ownerless actors (parent=None) are allowed via JWT with no ownership check;
246            # owned actors must still belong to the verified subject.
247            if actor.parent_id is not None and actor.parent_id != self.user.pk:
248                self.logger.warning("Actor is not controlled by the verified subject")
249                raise TokenExchangeError("invalid_grant").with_cause("actor_not_controlled")
250
251        self.actor = actor

RFC 8693 §4.1 delegation: validate an optional actor_token, identifying who is actually exercising the resulting token (e.g. an Actor acting for the verified subject_token's human).

Actors without an owner (parent=None) may only be used via a JWT actor_token. Actors with an owner may be used via a JWT or an authentik built-in Token, but only by the human that owns them (actor.parent_id == self.user.pk).