authentik.providers.oauth2.views.token

authentik OAuth2 Token views

  1"""authentik OAuth2 Token views"""
  2
  3from base64 import b64encode
  4from copy import copy
  5from datetime import datetime
  6from typing import Any
  7from uuid import uuid4
  8
  9from django.db import transaction
 10from django.http import HttpRequest, HttpResponse
 11from django.utils import timezone
 12from django.utils.decorators import method_decorator
 13from django.views import View
 14from django.views.decorators.csrf import csrf_exempt
 15from structlog.stdlib import get_logger
 16
 17from authentik.common.oauth.constants import (
 18    GRANT_TYPE_AUTHORIZATION_CODE,
 19    GRANT_TYPE_CLIENT_CREDENTIALS,
 20    GRANT_TYPE_DEVICE_CODE,
 21    GRANT_TYPE_PASSWORD,
 22    GRANT_TYPE_REFRESH_TOKEN,
 23    GRANT_TYPE_TOKEN_EXCHANGE,
 24    JWT_TYPE_DPOP_ID_TOKEN,
 25    SCOPE_OFFLINE_ACCESS,
 26    TOKEN_TYPE,
 27    TOKEN_TYPE_URI_SAML2,
 28)
 29from authentik.core.middleware import CTX_AUTH_VIA
 30from authentik.core.models import UserActivity
 31from authentik.events.signals import get_login_event
 32from authentik.lib.tracing import active_tracer
 33from authentik.lib.utils.time import timedelta_from_string
 34from authentik.providers.oauth2.errors import (
 35    DeviceCodeError,
 36    TokenError,
 37    UserAuthError,
 38)
 39from authentik.providers.oauth2.id_token import IDToken
 40from authentik.providers.oauth2.models import (
 41    AccessToken,
 42    OAuth2Provider,
 43    OAuth2SessionLogin,
 44    RefreshToken,
 45)
 46from authentik.providers.oauth2.token.base import TokenRequest
 47from authentik.providers.oauth2.token.router import parse_token_request
 48from authentik.providers.oauth2.utils import (
 49    TokenResponse,
 50    cors_allow,
 51    extract_client_auth,
 52)
 53from authentik.providers.saml.processors.assertion import AssertionProcessor
 54from authentik.providers.saml.processors.authn_request_parser import AuthNRequest
 55
 56LOGGER = get_logger()
 57
 58
 59@method_decorator(csrf_exempt, name="dispatch")
 60class TokenView(View):
 61    """Generate tokens for clients"""
 62
 63    provider: OAuth2Provider | None = None
 64    params: TokenRequest | None = None
 65    provider_class = OAuth2Provider
 66
 67    def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
 68        response = super().dispatch(request, *args, **kwargs)
 69        cors_allow(self.request, response, self.provider.redirect_uris if self.provider else [])
 70        return response
 71
 72    def options(self, request: HttpRequest) -> HttpResponse:
 73        return TokenResponse({})
 74
 75    def post(self, request: HttpRequest) -> HttpResponse:
 76        """Generate tokens for clients"""
 77        try:
 78            with active_tracer().start_span(
 79                op="authentik.providers.oauth2.post.parse",
 80            ):
 81                client_id, client_secret = extract_client_auth(request)
 82                self.provider = self.provider_class.objects.filter(client_id=client_id).first()
 83                if not self.provider:
 84                    LOGGER.warning("OAuth2Provider does not exist", client_id=client_id)
 85                    raise TokenError("invalid_client")
 86                self.params = parse_token_request(request, self.provider, client_id, client_secret)
 87                CTX_AUTH_VIA.set("oauth_client_secret")
 88
 89            with active_tracer().start_span(
 90                op="authentik.providers.oauth2.post.response",
 91            ):
 92                if self.params.grant_type == GRANT_TYPE_AUTHORIZATION_CODE:
 93                    LOGGER.debug("Converting authorization code to access token")
 94                    return TokenResponse(self.create_code_response())
 95                if self.params.grant_type == GRANT_TYPE_REFRESH_TOKEN:
 96                    LOGGER.debug("Refreshing refresh token")
 97                    return TokenResponse(self.create_refresh_response())
 98                if self.params.grant_type in [GRANT_TYPE_CLIENT_CREDENTIALS, GRANT_TYPE_PASSWORD]:
 99                    LOGGER.debug("Client credentials/password grant")
100                    return TokenResponse(self.create_client_credentials_response())
101                if self.params.grant_type == GRANT_TYPE_DEVICE_CODE:
102                    LOGGER.debug("Device code grant")
103                    return TokenResponse(self.create_device_code_response())
104                if self.params.grant_type == GRANT_TYPE_TOKEN_EXCHANGE:
105                    LOGGER.debug("Token exchange grant")
106                    return TokenResponse(self.create_token_exchange_response())
107                raise TokenError("unsupported_grant_type")
108        except TokenError as error:
109            return TokenResponse(error.create_dict(request), status=400)
110        except UserAuthError as error:
111            return TokenResponse(error.create_dict(request), status=403)
112
113    def _get_id_token_jwt_type(self) -> str | None:
114        """Return dpop+id_token if key binding is active, else None"""
115        if self.params.dpop_jwk is not None:
116            return JWT_TYPE_DPOP_ID_TOKEN
117        return None
118
119    def _add_cnf_to_id_token(self, id_token: IDToken) -> None:
120        """Add cnf claim to ID Token when key binding is active"""
121        if self.params.dpop_jwk is not None:
122            id_token.cnf = {"jwk": self.params.dpop_jwk}
123
124    def create_code_response(self) -> dict[str, Any]:
125        """See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1"""
126        now = timezone.now()
127        access_token_expiry = now + timedelta_from_string(self.provider.access_token_validity)
128        # Shared by the access and refresh token, so both are revoked when reuse is detected
129        family = uuid4() if SCOPE_OFFLINE_ACCESS in self.params.authorization_code.scope else None
130        access_token = AccessToken(
131            provider=self.provider,
132            user=self.params.authorization_code.user,
133            expires=access_token_expiry,
134            # Keep same scopes as previous token
135            scope=self.params.authorization_code.scope,
136            auth_time=self.params.authorization_code.auth_time,
137            session=self.params.authorization_code.session,
138            family=family,
139        )
140        access_id_token = IDToken.new(
141            self.provider,
142            access_token,
143            self.request,
144        )
145        access_id_token.nonce = self.params.authorization_code.nonce
146        self._add_cnf_to_id_token(access_id_token)
147        access_token.id_token = access_id_token
148        access_token.save()
149        OAuth2SessionLogin.record(access_token, access_id_token)
150
151        id_token_jwt_type = self._get_id_token_jwt_type()
152        response = {
153            "access_token": access_token.token,
154            "token_type": TOKEN_TYPE,
155            "scope": " ".join(access_token.scope),
156            "expires_in": int(
157                timedelta_from_string(self.provider.access_token_validity).total_seconds()
158            ),
159            "id_token": access_token.id_token.to_jwt(self.provider, jwt_type=id_token_jwt_type),
160        }
161
162        if SCOPE_OFFLINE_ACCESS in self.params.authorization_code.scope:
163            refresh_token_expiry = now + timedelta_from_string(self.provider.refresh_token_validity)
164            refresh_token = RefreshToken(
165                user=self.params.authorization_code.user,
166                scope=self.params.authorization_code.scope,
167                expires=refresh_token_expiry,
168                provider=self.provider,
169                auth_time=self.params.authorization_code.auth_time,
170                session=self.params.authorization_code.session,
171                dpop_jkt=self.params.authorization_code.dpop_jkt,
172                family=family,
173            )
174            id_token = IDToken.new(
175                self.provider,
176                refresh_token,
177                self.request,
178            )
179            id_token.nonce = self.params.authorization_code.nonce
180            id_token.at_hash = access_token.at_hash
181            self._add_cnf_to_id_token(id_token)
182            refresh_token.id_token = id_token
183            refresh_token.save()
184            response["refresh_token"] = refresh_token.token
185
186        # Delete old code
187        self.params.authorization_code.delete()
188        return response
189
190    def create_refresh_response(self) -> dict[str, Any]:
191        """See https://datatracker.ietf.org/doc/html/rfc6749#section-6"""
192        unauthorized_scopes = set(self.params.scope) - set(self.params.refresh_token.scope)
193        if unauthorized_scopes:
194            raise TokenError("invalid_scope")
195        if SCOPE_OFFLINE_ACCESS not in self.params.scope:
196            raise TokenError("invalid_scope")
197        old_token = self.params.refresh_token
198        now = timezone.now()
199        refresh_token_threshold = timedelta_from_string(self.provider.refresh_token_threshold)
200        rotate = (
201            refresh_token_threshold.total_seconds() == 0
202            or (old_token.expires - now) < refresh_token_threshold
203        )
204        # Consuming the old token and issuing the new ones happen in one transaction, which
205        # holds the family's lock, so that a concurrent request rotating or revoking the family
206        # waits for this one to commit and then sees the tokens it issued
207        with transaction.atomic():
208            if self.params.claim(now, rotate):
209                return self._issue_refresh_response(old_token, now, rotate)
210        # Outside of the transaction, so that the family revocation is kept
211        self.params.reject_reuse(self.request)
212
213    def _issue_refresh_response(
214        self, old_token: RefreshToken, now: datetime, rotate: bool
215    ) -> dict[str, Any]:
216        """Issue a new access token, and a new refresh token if `rotate` is set, for a refresh
217        token which has been claimed"""
218        access_token_expiry = now + timedelta_from_string(self.provider.access_token_validity)
219        access_token = AccessToken(
220            provider=self.provider,
221            user=old_token.user,
222            expires=access_token_expiry,
223            # Keep same scopes as previous token
224            scope=old_token.scope,
225            auth_time=old_token.auth_time,
226            session=old_token.session,
227            family=old_token.family,
228        )
229        access_id_token = IDToken.new(
230            self.provider,
231            access_token,
232            self.request,
233        )
234        self._add_cnf_to_id_token(access_id_token)
235        access_token.id_token = access_id_token
236        access_token.save()
237        OAuth2SessionLogin.record(access_token, access_id_token)
238
239        id_token_jwt_type = self._get_id_token_jwt_type()
240        response = {
241            "access_token": access_token.token,
242            "token_type": TOKEN_TYPE,
243            "scope": " ".join(access_token.scope),
244            "expires_in": int(
245                timedelta_from_string(self.provider.access_token_validity).total_seconds()
246            ),
247            "id_token": access_token.id_token.to_jwt(self.provider, jwt_type=id_token_jwt_type),
248        }
249
250        if rotate:
251            refresh_token_expiry = now + timedelta_from_string(self.provider.refresh_token_validity)
252            refresh_token = RefreshToken(
253                user=old_token.user,
254                scope=old_token.scope,
255                expires=refresh_token_expiry,
256                provider=self.provider,
257                auth_time=old_token.auth_time,
258                session=old_token.session,
259                dpop_jkt=old_token.dpop_jkt,
260                family=old_token.family,
261            )
262            id_token = IDToken.new(
263                self.provider,
264                refresh_token,
265                self.request,
266            )
267            id_token.nonce = old_token.id_token.nonce
268            id_token.at_hash = access_token.at_hash
269            self._add_cnf_to_id_token(id_token)
270            refresh_token.id_token = id_token
271            refresh_token.save()
272            # The old token was already marked as rotated by `claim`
273            response["refresh_token"] = refresh_token.token
274
275        # Refreshes come from the client without a browser session, so check the session
276        # the token was issued from. During impersonation it belongs to the admin.
277        token = self.params.refresh_token
278        if token.session is None or token.session.user_id == token.user_id:
279            UserActivity.objects.record(token.user_id, now)
280
281        return response
282
283    def create_client_credentials_response(self) -> dict[str, Any]:
284        """See https://datatracker.ietf.org/doc/html/rfc6749#section-4.4"""
285        now = timezone.now()
286        access_token_expiry = now + timedelta_from_string(self.provider.access_token_validity)
287        access_token = AccessToken(
288            provider=self.provider,
289            user=self.params.user,
290            expires=access_token_expiry,
291            scope=self.params.scope,
292            auth_time=now,
293        )
294        access_token.id_token = IDToken.new(
295            self.provider,
296            access_token,
297            self.request,
298        )
299        access_token.save()
300        return {
301            "access_token": access_token.token,
302            "token_type": TOKEN_TYPE,
303            "scope": " ".join(access_token.scope),
304            "expires_in": int(
305                timedelta_from_string(self.provider.access_token_validity).total_seconds()
306            ),
307            "id_token": access_token.id_token.to_jwt(self.provider),
308        }
309
310    def create_device_code_response(self) -> dict[str, Any]:
311        """See https://datatracker.ietf.org/doc/html/rfc8628"""
312        if not self.params.device_code.user:
313            raise DeviceCodeError("authorization_pending")
314        now = timezone.now()
315        access_token_expiry = now + timedelta_from_string(self.provider.access_token_validity)
316        auth_event = get_login_event(self.params.device_code.session)
317        # Shared by the access and refresh token, so both are revoked when reuse is detected
318        family = uuid4() if SCOPE_OFFLINE_ACCESS in self.params.device_code.scope else None
319        access_token = AccessToken(
320            provider=self.provider,
321            user=self.params.device_code.user,
322            expires=access_token_expiry,
323            scope=self.params.device_code.scope,
324            auth_time=auth_event.created if auth_event else now,
325            session=self.params.device_code.session,
326            family=family,
327        )
328        access_id_token = IDToken.new(
329            self.provider,
330            access_token,
331            self.request,
332        )
333        self._add_cnf_to_id_token(access_id_token)
334        access_token.id_token = access_id_token
335        access_token.save()
336        OAuth2SessionLogin.record(access_token, access_id_token)
337
338        id_token_jwt_type = self._get_id_token_jwt_type()
339        response = {
340            "access_token": access_token.token,
341            "token_type": TOKEN_TYPE,
342            "scope": " ".join(access_token.scope),
343            "expires_in": int(
344                timedelta_from_string(self.provider.access_token_validity).total_seconds()
345            ),
346            "id_token": access_token.id_token.to_jwt(self.provider, jwt_type=id_token_jwt_type),
347        }
348
349        if SCOPE_OFFLINE_ACCESS in self.params.device_code.scope:
350            refresh_token_expiry = now + timedelta_from_string(self.provider.refresh_token_validity)
351            refresh_token = RefreshToken(
352                user=self.params.device_code.user,
353                scope=self.params.device_code.scope,
354                expires=refresh_token_expiry,
355                provider=self.provider,
356                auth_time=auth_event.created if auth_event else now,
357                dpop_jkt=self.params.device_code.dpop_jkt,
358                family=family,
359            )
360            id_token = IDToken.new(
361                self.provider,
362                refresh_token,
363                self.request,
364            )
365            id_token.at_hash = access_token.at_hash
366            self._add_cnf_to_id_token(id_token)
367            refresh_token.id_token = id_token
368            refresh_token.save()
369            response["refresh_token"] = refresh_token.token
370
371        # Delete device code
372        self.params.device_code.delete()
373        return response
374
375    def create_saml_token_exchange_response(self) -> dict[str, Any]:
376        """IdP-initiated SAML Response for the federated SAML provider, base64-encoded
377        like the SAMLResponse form field, so it can be passed on as-is
378        (e.g. to AWS STS AssumeRoleWithSAML)."""
379        provider = self.params.saml_provider
380        request = copy(self.request)
381        request.user = self.params.user
382        response = AssertionProcessor(provider, request, AuthNRequest()).build_response()
383        return {
384            "access_token": b64encode(response.encode()).decode(),
385            "issued_token_type": TOKEN_TYPE_URI_SAML2,
386            # RFC 8693 ยง2.2.1: the issued token is not an OAuth access token
387            "token_type": "N_A",
388            "expires_in": int(
389                timedelta_from_string(provider.assertion_valid_not_on_or_after).total_seconds()
390            ),
391        }
392
393    def create_token_exchange_response(self) -> dict[str, Any]:
394        """See https://datatracker.ietf.org/doc/html/rfc8693#section-2.2.1"""
395        if self.params.saml_provider:
396            return self.create_saml_token_exchange_response()
397        # Issued on the `audience` target, else on the client's own provider
398        provider = self.params.token_provider
399        now = timezone.now()
400        access_token_expiry = now + timedelta_from_string(provider.access_token_validity)
401        access_token = AccessToken(
402            provider=provider,
403            user=self.params.user,
404            actor=self.params.actor,
405            expires=access_token_expiry,
406            scope=self.params.scope,
407            auth_time=now,
408        )
409        access_token.id_token = IDToken.new(
410            provider,
411            access_token,
412            self.request,
413            act=self.params.prior_act,
414        )
415        access_token.save()
416
417        return {
418            "access_token": access_token.token,
419            # Access tokens are themselves JWTs, so the issued token satisfies either
420            # identifier the client may have requested.
421            "issued_token_type": self.params.requested_token_type,
422            "token_type": TOKEN_TYPE,
423            "scope": " ".join(access_token.scope),
424            "expires_in": int(
425                timedelta_from_string(provider.access_token_validity).total_seconds()
426            ),
427        }
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
@method_decorator(csrf_exempt, name='dispatch')
class TokenView(django.views.generic.base.View):
 60@method_decorator(csrf_exempt, name="dispatch")
 61class TokenView(View):
 62    """Generate tokens for clients"""
 63
 64    provider: OAuth2Provider | None = None
 65    params: TokenRequest | None = None
 66    provider_class = OAuth2Provider
 67
 68    def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
 69        response = super().dispatch(request, *args, **kwargs)
 70        cors_allow(self.request, response, self.provider.redirect_uris if self.provider else [])
 71        return response
 72
 73    def options(self, request: HttpRequest) -> HttpResponse:
 74        return TokenResponse({})
 75
 76    def post(self, request: HttpRequest) -> HttpResponse:
 77        """Generate tokens for clients"""
 78        try:
 79            with active_tracer().start_span(
 80                op="authentik.providers.oauth2.post.parse",
 81            ):
 82                client_id, client_secret = extract_client_auth(request)
 83                self.provider = self.provider_class.objects.filter(client_id=client_id).first()
 84                if not self.provider:
 85                    LOGGER.warning("OAuth2Provider does not exist", client_id=client_id)
 86                    raise TokenError("invalid_client")
 87                self.params = parse_token_request(request, self.provider, client_id, client_secret)
 88                CTX_AUTH_VIA.set("oauth_client_secret")
 89
 90            with active_tracer().start_span(
 91                op="authentik.providers.oauth2.post.response",
 92            ):
 93                if self.params.grant_type == GRANT_TYPE_AUTHORIZATION_CODE:
 94                    LOGGER.debug("Converting authorization code to access token")
 95                    return TokenResponse(self.create_code_response())
 96                if self.params.grant_type == GRANT_TYPE_REFRESH_TOKEN:
 97                    LOGGER.debug("Refreshing refresh token")
 98                    return TokenResponse(self.create_refresh_response())
 99                if self.params.grant_type in [GRANT_TYPE_CLIENT_CREDENTIALS, GRANT_TYPE_PASSWORD]:
100                    LOGGER.debug("Client credentials/password grant")
101                    return TokenResponse(self.create_client_credentials_response())
102                if self.params.grant_type == GRANT_TYPE_DEVICE_CODE:
103                    LOGGER.debug("Device code grant")
104                    return TokenResponse(self.create_device_code_response())
105                if self.params.grant_type == GRANT_TYPE_TOKEN_EXCHANGE:
106                    LOGGER.debug("Token exchange grant")
107                    return TokenResponse(self.create_token_exchange_response())
108                raise TokenError("unsupported_grant_type")
109        except TokenError as error:
110            return TokenResponse(error.create_dict(request), status=400)
111        except UserAuthError as error:
112            return TokenResponse(error.create_dict(request), status=403)
113
114    def _get_id_token_jwt_type(self) -> str | None:
115        """Return dpop+id_token if key binding is active, else None"""
116        if self.params.dpop_jwk is not None:
117            return JWT_TYPE_DPOP_ID_TOKEN
118        return None
119
120    def _add_cnf_to_id_token(self, id_token: IDToken) -> None:
121        """Add cnf claim to ID Token when key binding is active"""
122        if self.params.dpop_jwk is not None:
123            id_token.cnf = {"jwk": self.params.dpop_jwk}
124
125    def create_code_response(self) -> dict[str, Any]:
126        """See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1"""
127        now = timezone.now()
128        access_token_expiry = now + timedelta_from_string(self.provider.access_token_validity)
129        # Shared by the access and refresh token, so both are revoked when reuse is detected
130        family = uuid4() if SCOPE_OFFLINE_ACCESS in self.params.authorization_code.scope else None
131        access_token = AccessToken(
132            provider=self.provider,
133            user=self.params.authorization_code.user,
134            expires=access_token_expiry,
135            # Keep same scopes as previous token
136            scope=self.params.authorization_code.scope,
137            auth_time=self.params.authorization_code.auth_time,
138            session=self.params.authorization_code.session,
139            family=family,
140        )
141        access_id_token = IDToken.new(
142            self.provider,
143            access_token,
144            self.request,
145        )
146        access_id_token.nonce = self.params.authorization_code.nonce
147        self._add_cnf_to_id_token(access_id_token)
148        access_token.id_token = access_id_token
149        access_token.save()
150        OAuth2SessionLogin.record(access_token, access_id_token)
151
152        id_token_jwt_type = self._get_id_token_jwt_type()
153        response = {
154            "access_token": access_token.token,
155            "token_type": TOKEN_TYPE,
156            "scope": " ".join(access_token.scope),
157            "expires_in": int(
158                timedelta_from_string(self.provider.access_token_validity).total_seconds()
159            ),
160            "id_token": access_token.id_token.to_jwt(self.provider, jwt_type=id_token_jwt_type),
161        }
162
163        if SCOPE_OFFLINE_ACCESS in self.params.authorization_code.scope:
164            refresh_token_expiry = now + timedelta_from_string(self.provider.refresh_token_validity)
165            refresh_token = RefreshToken(
166                user=self.params.authorization_code.user,
167                scope=self.params.authorization_code.scope,
168                expires=refresh_token_expiry,
169                provider=self.provider,
170                auth_time=self.params.authorization_code.auth_time,
171                session=self.params.authorization_code.session,
172                dpop_jkt=self.params.authorization_code.dpop_jkt,
173                family=family,
174            )
175            id_token = IDToken.new(
176                self.provider,
177                refresh_token,
178                self.request,
179            )
180            id_token.nonce = self.params.authorization_code.nonce
181            id_token.at_hash = access_token.at_hash
182            self._add_cnf_to_id_token(id_token)
183            refresh_token.id_token = id_token
184            refresh_token.save()
185            response["refresh_token"] = refresh_token.token
186
187        # Delete old code
188        self.params.authorization_code.delete()
189        return response
190
191    def create_refresh_response(self) -> dict[str, Any]:
192        """See https://datatracker.ietf.org/doc/html/rfc6749#section-6"""
193        unauthorized_scopes = set(self.params.scope) - set(self.params.refresh_token.scope)
194        if unauthorized_scopes:
195            raise TokenError("invalid_scope")
196        if SCOPE_OFFLINE_ACCESS not in self.params.scope:
197            raise TokenError("invalid_scope")
198        old_token = self.params.refresh_token
199        now = timezone.now()
200        refresh_token_threshold = timedelta_from_string(self.provider.refresh_token_threshold)
201        rotate = (
202            refresh_token_threshold.total_seconds() == 0
203            or (old_token.expires - now) < refresh_token_threshold
204        )
205        # Consuming the old token and issuing the new ones happen in one transaction, which
206        # holds the family's lock, so that a concurrent request rotating or revoking the family
207        # waits for this one to commit and then sees the tokens it issued
208        with transaction.atomic():
209            if self.params.claim(now, rotate):
210                return self._issue_refresh_response(old_token, now, rotate)
211        # Outside of the transaction, so that the family revocation is kept
212        self.params.reject_reuse(self.request)
213
214    def _issue_refresh_response(
215        self, old_token: RefreshToken, now: datetime, rotate: bool
216    ) -> dict[str, Any]:
217        """Issue a new access token, and a new refresh token if `rotate` is set, for a refresh
218        token which has been claimed"""
219        access_token_expiry = now + timedelta_from_string(self.provider.access_token_validity)
220        access_token = AccessToken(
221            provider=self.provider,
222            user=old_token.user,
223            expires=access_token_expiry,
224            # Keep same scopes as previous token
225            scope=old_token.scope,
226            auth_time=old_token.auth_time,
227            session=old_token.session,
228            family=old_token.family,
229        )
230        access_id_token = IDToken.new(
231            self.provider,
232            access_token,
233            self.request,
234        )
235        self._add_cnf_to_id_token(access_id_token)
236        access_token.id_token = access_id_token
237        access_token.save()
238        OAuth2SessionLogin.record(access_token, access_id_token)
239
240        id_token_jwt_type = self._get_id_token_jwt_type()
241        response = {
242            "access_token": access_token.token,
243            "token_type": TOKEN_TYPE,
244            "scope": " ".join(access_token.scope),
245            "expires_in": int(
246                timedelta_from_string(self.provider.access_token_validity).total_seconds()
247            ),
248            "id_token": access_token.id_token.to_jwt(self.provider, jwt_type=id_token_jwt_type),
249        }
250
251        if rotate:
252            refresh_token_expiry = now + timedelta_from_string(self.provider.refresh_token_validity)
253            refresh_token = RefreshToken(
254                user=old_token.user,
255                scope=old_token.scope,
256                expires=refresh_token_expiry,
257                provider=self.provider,
258                auth_time=old_token.auth_time,
259                session=old_token.session,
260                dpop_jkt=old_token.dpop_jkt,
261                family=old_token.family,
262            )
263            id_token = IDToken.new(
264                self.provider,
265                refresh_token,
266                self.request,
267            )
268            id_token.nonce = old_token.id_token.nonce
269            id_token.at_hash = access_token.at_hash
270            self._add_cnf_to_id_token(id_token)
271            refresh_token.id_token = id_token
272            refresh_token.save()
273            # The old token was already marked as rotated by `claim`
274            response["refresh_token"] = refresh_token.token
275
276        # Refreshes come from the client without a browser session, so check the session
277        # the token was issued from. During impersonation it belongs to the admin.
278        token = self.params.refresh_token
279        if token.session is None or token.session.user_id == token.user_id:
280            UserActivity.objects.record(token.user_id, now)
281
282        return response
283
284    def create_client_credentials_response(self) -> dict[str, Any]:
285        """See https://datatracker.ietf.org/doc/html/rfc6749#section-4.4"""
286        now = timezone.now()
287        access_token_expiry = now + timedelta_from_string(self.provider.access_token_validity)
288        access_token = AccessToken(
289            provider=self.provider,
290            user=self.params.user,
291            expires=access_token_expiry,
292            scope=self.params.scope,
293            auth_time=now,
294        )
295        access_token.id_token = IDToken.new(
296            self.provider,
297            access_token,
298            self.request,
299        )
300        access_token.save()
301        return {
302            "access_token": access_token.token,
303            "token_type": TOKEN_TYPE,
304            "scope": " ".join(access_token.scope),
305            "expires_in": int(
306                timedelta_from_string(self.provider.access_token_validity).total_seconds()
307            ),
308            "id_token": access_token.id_token.to_jwt(self.provider),
309        }
310
311    def create_device_code_response(self) -> dict[str, Any]:
312        """See https://datatracker.ietf.org/doc/html/rfc8628"""
313        if not self.params.device_code.user:
314            raise DeviceCodeError("authorization_pending")
315        now = timezone.now()
316        access_token_expiry = now + timedelta_from_string(self.provider.access_token_validity)
317        auth_event = get_login_event(self.params.device_code.session)
318        # Shared by the access and refresh token, so both are revoked when reuse is detected
319        family = uuid4() if SCOPE_OFFLINE_ACCESS in self.params.device_code.scope else None
320        access_token = AccessToken(
321            provider=self.provider,
322            user=self.params.device_code.user,
323            expires=access_token_expiry,
324            scope=self.params.device_code.scope,
325            auth_time=auth_event.created if auth_event else now,
326            session=self.params.device_code.session,
327            family=family,
328        )
329        access_id_token = IDToken.new(
330            self.provider,
331            access_token,
332            self.request,
333        )
334        self._add_cnf_to_id_token(access_id_token)
335        access_token.id_token = access_id_token
336        access_token.save()
337        OAuth2SessionLogin.record(access_token, access_id_token)
338
339        id_token_jwt_type = self._get_id_token_jwt_type()
340        response = {
341            "access_token": access_token.token,
342            "token_type": TOKEN_TYPE,
343            "scope": " ".join(access_token.scope),
344            "expires_in": int(
345                timedelta_from_string(self.provider.access_token_validity).total_seconds()
346            ),
347            "id_token": access_token.id_token.to_jwt(self.provider, jwt_type=id_token_jwt_type),
348        }
349
350        if SCOPE_OFFLINE_ACCESS in self.params.device_code.scope:
351            refresh_token_expiry = now + timedelta_from_string(self.provider.refresh_token_validity)
352            refresh_token = RefreshToken(
353                user=self.params.device_code.user,
354                scope=self.params.device_code.scope,
355                expires=refresh_token_expiry,
356                provider=self.provider,
357                auth_time=auth_event.created if auth_event else now,
358                dpop_jkt=self.params.device_code.dpop_jkt,
359                family=family,
360            )
361            id_token = IDToken.new(
362                self.provider,
363                refresh_token,
364                self.request,
365            )
366            id_token.at_hash = access_token.at_hash
367            self._add_cnf_to_id_token(id_token)
368            refresh_token.id_token = id_token
369            refresh_token.save()
370            response["refresh_token"] = refresh_token.token
371
372        # Delete device code
373        self.params.device_code.delete()
374        return response
375
376    def create_saml_token_exchange_response(self) -> dict[str, Any]:
377        """IdP-initiated SAML Response for the federated SAML provider, base64-encoded
378        like the SAMLResponse form field, so it can be passed on as-is
379        (e.g. to AWS STS AssumeRoleWithSAML)."""
380        provider = self.params.saml_provider
381        request = copy(self.request)
382        request.user = self.params.user
383        response = AssertionProcessor(provider, request, AuthNRequest()).build_response()
384        return {
385            "access_token": b64encode(response.encode()).decode(),
386            "issued_token_type": TOKEN_TYPE_URI_SAML2,
387            # RFC 8693 ยง2.2.1: the issued token is not an OAuth access token
388            "token_type": "N_A",
389            "expires_in": int(
390                timedelta_from_string(provider.assertion_valid_not_on_or_after).total_seconds()
391            ),
392        }
393
394    def create_token_exchange_response(self) -> dict[str, Any]:
395        """See https://datatracker.ietf.org/doc/html/rfc8693#section-2.2.1"""
396        if self.params.saml_provider:
397            return self.create_saml_token_exchange_response()
398        # Issued on the `audience` target, else on the client's own provider
399        provider = self.params.token_provider
400        now = timezone.now()
401        access_token_expiry = now + timedelta_from_string(provider.access_token_validity)
402        access_token = AccessToken(
403            provider=provider,
404            user=self.params.user,
405            actor=self.params.actor,
406            expires=access_token_expiry,
407            scope=self.params.scope,
408            auth_time=now,
409        )
410        access_token.id_token = IDToken.new(
411            provider,
412            access_token,
413            self.request,
414            act=self.params.prior_act,
415        )
416        access_token.save()
417
418        return {
419            "access_token": access_token.token,
420            # Access tokens are themselves JWTs, so the issued token satisfies either
421            # identifier the client may have requested.
422            "issued_token_type": self.params.requested_token_type,
423            "token_type": TOKEN_TYPE,
424            "scope": " ".join(access_token.scope),
425            "expires_in": int(
426                timedelta_from_string(provider.access_token_validity).total_seconds()
427            ),
428        }

Generate tokens for clients

def dispatch( self, request: django.http.request.HttpRequest, *args: Any, **kwargs: Any) -> django.http.response.HttpResponse:
68    def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
69        response = super().dispatch(request, *args, **kwargs)
70        cors_allow(self.request, response, self.provider.redirect_uris if self.provider else [])
71        return response
def options( self, request: django.http.request.HttpRequest) -> django.http.response.HttpResponse:
73    def options(self, request: HttpRequest) -> HttpResponse:
74        return TokenResponse({})

Handle responding to requests for the OPTIONS HTTP verb.

def post( self, request: django.http.request.HttpRequest) -> django.http.response.HttpResponse:
 76    def post(self, request: HttpRequest) -> HttpResponse:
 77        """Generate tokens for clients"""
 78        try:
 79            with active_tracer().start_span(
 80                op="authentik.providers.oauth2.post.parse",
 81            ):
 82                client_id, client_secret = extract_client_auth(request)
 83                self.provider = self.provider_class.objects.filter(client_id=client_id).first()
 84                if not self.provider:
 85                    LOGGER.warning("OAuth2Provider does not exist", client_id=client_id)
 86                    raise TokenError("invalid_client")
 87                self.params = parse_token_request(request, self.provider, client_id, client_secret)
 88                CTX_AUTH_VIA.set("oauth_client_secret")
 89
 90            with active_tracer().start_span(
 91                op="authentik.providers.oauth2.post.response",
 92            ):
 93                if self.params.grant_type == GRANT_TYPE_AUTHORIZATION_CODE:
 94                    LOGGER.debug("Converting authorization code to access token")
 95                    return TokenResponse(self.create_code_response())
 96                if self.params.grant_type == GRANT_TYPE_REFRESH_TOKEN:
 97                    LOGGER.debug("Refreshing refresh token")
 98                    return TokenResponse(self.create_refresh_response())
 99                if self.params.grant_type in [GRANT_TYPE_CLIENT_CREDENTIALS, GRANT_TYPE_PASSWORD]:
100                    LOGGER.debug("Client credentials/password grant")
101                    return TokenResponse(self.create_client_credentials_response())
102                if self.params.grant_type == GRANT_TYPE_DEVICE_CODE:
103                    LOGGER.debug("Device code grant")
104                    return TokenResponse(self.create_device_code_response())
105                if self.params.grant_type == GRANT_TYPE_TOKEN_EXCHANGE:
106                    LOGGER.debug("Token exchange grant")
107                    return TokenResponse(self.create_token_exchange_response())
108                raise TokenError("unsupported_grant_type")
109        except TokenError as error:
110            return TokenResponse(error.create_dict(request), status=400)
111        except UserAuthError as error:
112            return TokenResponse(error.create_dict(request), status=403)

Generate tokens for clients

def create_code_response(self) -> dict[str, typing.Any]:
125    def create_code_response(self) -> dict[str, Any]:
126        """See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1"""
127        now = timezone.now()
128        access_token_expiry = now + timedelta_from_string(self.provider.access_token_validity)
129        # Shared by the access and refresh token, so both are revoked when reuse is detected
130        family = uuid4() if SCOPE_OFFLINE_ACCESS in self.params.authorization_code.scope else None
131        access_token = AccessToken(
132            provider=self.provider,
133            user=self.params.authorization_code.user,
134            expires=access_token_expiry,
135            # Keep same scopes as previous token
136            scope=self.params.authorization_code.scope,
137            auth_time=self.params.authorization_code.auth_time,
138            session=self.params.authorization_code.session,
139            family=family,
140        )
141        access_id_token = IDToken.new(
142            self.provider,
143            access_token,
144            self.request,
145        )
146        access_id_token.nonce = self.params.authorization_code.nonce
147        self._add_cnf_to_id_token(access_id_token)
148        access_token.id_token = access_id_token
149        access_token.save()
150        OAuth2SessionLogin.record(access_token, access_id_token)
151
152        id_token_jwt_type = self._get_id_token_jwt_type()
153        response = {
154            "access_token": access_token.token,
155            "token_type": TOKEN_TYPE,
156            "scope": " ".join(access_token.scope),
157            "expires_in": int(
158                timedelta_from_string(self.provider.access_token_validity).total_seconds()
159            ),
160            "id_token": access_token.id_token.to_jwt(self.provider, jwt_type=id_token_jwt_type),
161        }
162
163        if SCOPE_OFFLINE_ACCESS in self.params.authorization_code.scope:
164            refresh_token_expiry = now + timedelta_from_string(self.provider.refresh_token_validity)
165            refresh_token = RefreshToken(
166                user=self.params.authorization_code.user,
167                scope=self.params.authorization_code.scope,
168                expires=refresh_token_expiry,
169                provider=self.provider,
170                auth_time=self.params.authorization_code.auth_time,
171                session=self.params.authorization_code.session,
172                dpop_jkt=self.params.authorization_code.dpop_jkt,
173                family=family,
174            )
175            id_token = IDToken.new(
176                self.provider,
177                refresh_token,
178                self.request,
179            )
180            id_token.nonce = self.params.authorization_code.nonce
181            id_token.at_hash = access_token.at_hash
182            self._add_cnf_to_id_token(id_token)
183            refresh_token.id_token = id_token
184            refresh_token.save()
185            response["refresh_token"] = refresh_token.token
186
187        # Delete old code
188        self.params.authorization_code.delete()
189        return response
def create_refresh_response(self) -> dict[str, typing.Any]:
191    def create_refresh_response(self) -> dict[str, Any]:
192        """See https://datatracker.ietf.org/doc/html/rfc6749#section-6"""
193        unauthorized_scopes = set(self.params.scope) - set(self.params.refresh_token.scope)
194        if unauthorized_scopes:
195            raise TokenError("invalid_scope")
196        if SCOPE_OFFLINE_ACCESS not in self.params.scope:
197            raise TokenError("invalid_scope")
198        old_token = self.params.refresh_token
199        now = timezone.now()
200        refresh_token_threshold = timedelta_from_string(self.provider.refresh_token_threshold)
201        rotate = (
202            refresh_token_threshold.total_seconds() == 0
203            or (old_token.expires - now) < refresh_token_threshold
204        )
205        # Consuming the old token and issuing the new ones happen in one transaction, which
206        # holds the family's lock, so that a concurrent request rotating or revoking the family
207        # waits for this one to commit and then sees the tokens it issued
208        with transaction.atomic():
209            if self.params.claim(now, rotate):
210                return self._issue_refresh_response(old_token, now, rotate)
211        # Outside of the transaction, so that the family revocation is kept
212        self.params.reject_reuse(self.request)
def create_client_credentials_response(self) -> dict[str, typing.Any]:
284    def create_client_credentials_response(self) -> dict[str, Any]:
285        """See https://datatracker.ietf.org/doc/html/rfc6749#section-4.4"""
286        now = timezone.now()
287        access_token_expiry = now + timedelta_from_string(self.provider.access_token_validity)
288        access_token = AccessToken(
289            provider=self.provider,
290            user=self.params.user,
291            expires=access_token_expiry,
292            scope=self.params.scope,
293            auth_time=now,
294        )
295        access_token.id_token = IDToken.new(
296            self.provider,
297            access_token,
298            self.request,
299        )
300        access_token.save()
301        return {
302            "access_token": access_token.token,
303            "token_type": TOKEN_TYPE,
304            "scope": " ".join(access_token.scope),
305            "expires_in": int(
306                timedelta_from_string(self.provider.access_token_validity).total_seconds()
307            ),
308            "id_token": access_token.id_token.to_jwt(self.provider),
309        }
def create_device_code_response(self) -> dict[str, typing.Any]:
311    def create_device_code_response(self) -> dict[str, Any]:
312        """See https://datatracker.ietf.org/doc/html/rfc8628"""
313        if not self.params.device_code.user:
314            raise DeviceCodeError("authorization_pending")
315        now = timezone.now()
316        access_token_expiry = now + timedelta_from_string(self.provider.access_token_validity)
317        auth_event = get_login_event(self.params.device_code.session)
318        # Shared by the access and refresh token, so both are revoked when reuse is detected
319        family = uuid4() if SCOPE_OFFLINE_ACCESS in self.params.device_code.scope else None
320        access_token = AccessToken(
321            provider=self.provider,
322            user=self.params.device_code.user,
323            expires=access_token_expiry,
324            scope=self.params.device_code.scope,
325            auth_time=auth_event.created if auth_event else now,
326            session=self.params.device_code.session,
327            family=family,
328        )
329        access_id_token = IDToken.new(
330            self.provider,
331            access_token,
332            self.request,
333        )
334        self._add_cnf_to_id_token(access_id_token)
335        access_token.id_token = access_id_token
336        access_token.save()
337        OAuth2SessionLogin.record(access_token, access_id_token)
338
339        id_token_jwt_type = self._get_id_token_jwt_type()
340        response = {
341            "access_token": access_token.token,
342            "token_type": TOKEN_TYPE,
343            "scope": " ".join(access_token.scope),
344            "expires_in": int(
345                timedelta_from_string(self.provider.access_token_validity).total_seconds()
346            ),
347            "id_token": access_token.id_token.to_jwt(self.provider, jwt_type=id_token_jwt_type),
348        }
349
350        if SCOPE_OFFLINE_ACCESS in self.params.device_code.scope:
351            refresh_token_expiry = now + timedelta_from_string(self.provider.refresh_token_validity)
352            refresh_token = RefreshToken(
353                user=self.params.device_code.user,
354                scope=self.params.device_code.scope,
355                expires=refresh_token_expiry,
356                provider=self.provider,
357                auth_time=auth_event.created if auth_event else now,
358                dpop_jkt=self.params.device_code.dpop_jkt,
359                family=family,
360            )
361            id_token = IDToken.new(
362                self.provider,
363                refresh_token,
364                self.request,
365            )
366            id_token.at_hash = access_token.at_hash
367            self._add_cnf_to_id_token(id_token)
368            refresh_token.id_token = id_token
369            refresh_token.save()
370            response["refresh_token"] = refresh_token.token
371
372        # Delete device code
373        self.params.device_code.delete()
374        return response
def create_saml_token_exchange_response(self) -> dict[str, typing.Any]:
376    def create_saml_token_exchange_response(self) -> dict[str, Any]:
377        """IdP-initiated SAML Response for the federated SAML provider, base64-encoded
378        like the SAMLResponse form field, so it can be passed on as-is
379        (e.g. to AWS STS AssumeRoleWithSAML)."""
380        provider = self.params.saml_provider
381        request = copy(self.request)
382        request.user = self.params.user
383        response = AssertionProcessor(provider, request, AuthNRequest()).build_response()
384        return {
385            "access_token": b64encode(response.encode()).decode(),
386            "issued_token_type": TOKEN_TYPE_URI_SAML2,
387            # RFC 8693 ยง2.2.1: the issued token is not an OAuth access token
388            "token_type": "N_A",
389            "expires_in": int(
390                timedelta_from_string(provider.assertion_valid_not_on_or_after).total_seconds()
391            ),
392        }

IdP-initiated SAML Response for the federated SAML provider, base64-encoded like the SAMLResponse form field, so it can be passed on as-is (e.g. to AWS STS AssumeRoleWithSAML).

def create_token_exchange_response(self) -> dict[str, typing.Any]:
394    def create_token_exchange_response(self) -> dict[str, Any]:
395        """See https://datatracker.ietf.org/doc/html/rfc8693#section-2.2.1"""
396        if self.params.saml_provider:
397            return self.create_saml_token_exchange_response()
398        # Issued on the `audience` target, else on the client's own provider
399        provider = self.params.token_provider
400        now = timezone.now()
401        access_token_expiry = now + timedelta_from_string(provider.access_token_validity)
402        access_token = AccessToken(
403            provider=provider,
404            user=self.params.user,
405            actor=self.params.actor,
406            expires=access_token_expiry,
407            scope=self.params.scope,
408            auth_time=now,
409        )
410        access_token.id_token = IDToken.new(
411            provider,
412            access_token,
413            self.request,
414            act=self.params.prior_act,
415        )
416        access_token.save()
417
418        return {
419            "access_token": access_token.token,
420            # Access tokens are themselves JWTs, so the issued token satisfies either
421            # identifier the client may have requested.
422            "issued_token_type": self.params.requested_token_type,
423            "token_type": TOKEN_TYPE,
424            "scope": " ".join(access_token.scope),
425            "expires_in": int(
426                timedelta_from_string(provider.access_token_validity).total_seconds()
427            ),
428        }