authentik.providers.oauth2.models

OAuth Provider Models

   1"""OAuth Provider Models"""
   2
   3import base64
   4import binascii
   5import json
   6from dataclasses import asdict, dataclass
   7from datetime import datetime
   8from functools import cached_property
   9from hashlib import sha256
  10from typing import TYPE_CHECKING, Any
  11from urllib.parse import urlparse, urlunparse
  12from uuid import UUID, uuid4
  13
  14from cryptography.hazmat.primitives.asymmetric.ec import (
  15    SECP256R1,
  16    SECP384R1,
  17    SECP521R1,
  18    EllipticCurvePublicKey,
  19)
  20from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PublicKey
  21from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
  22from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
  23from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes, PublicKeyTypes
  24from dacite import Config
  25from dacite.core import from_dict
  26from django.contrib.postgres.fields import ArrayField
  27from django.contrib.postgres.indexes import HashIndex
  28from django.db import connection, models, transaction
  29from django.db.models import Exists, F, OuterRef, Q
  30from django.db.transaction import TransactionManagementError
  31from django.http import HttpRequest
  32from django.templatetags.static import static
  33from django.urls import reverse
  34from django.utils.translation import gettext_lazy as _
  35from jwcrypto.common import json_encode
  36from jwcrypto.jwe import JWE
  37from jwcrypto.jwk import JWK
  38from jwt import encode
  39from rest_framework.serializers import Serializer
  40from structlog.stdlib import get_logger
  41
  42from authentik.brands.models import WebfingerProvider
  43from authentik.common.oauth.constants import (
  44    GRANT_TYPE_AUTHORIZATION_CODE,
  45    GRANT_TYPE_CLIENT_CREDENTIALS,
  46    GRANT_TYPE_DEVICE_CODE,
  47    GRANT_TYPE_HYBRID,
  48    GRANT_TYPE_IMPLICIT,
  49    GRANT_TYPE_PASSWORD,
  50    GRANT_TYPE_REFRESH_TOKEN,
  51    GRANT_TYPE_TOKEN_EXCHANGE,
  52    SubModes,
  53)
  54from authentik.core.models import (
  55    AuthenticatedSession,
  56    PropertyMapping,
  57    Provider,
  58    User,
  59)
  60from authentik.crypto.models import CertificateKeyPair
  61from authentik.lib.generators import generate_code_fixed_length, generate_id, generate_key
  62from authentik.lib.jwt_mldsa import MLDSAAlgorithm, MLDSAKey
  63from authentik.lib.models import (
  64    DomainlessURLValidator,
  65    ExpiringModel,
  66    InternallyManagedMixin,
  67    SerializerModel,
  68    SimpleThroughModel,
  69)
  70from authentik.lib.tracing import active_tracer
  71from authentik.lib.utils.time import timedelta_string_validator
  72from authentik.policies.models import PolicyBindingModel
  73from authentik.sources.oauth.models import OAuthSource
  74
  75if TYPE_CHECKING:
  76    from authentik.providers.oauth2.id_token import IDToken
  77
  78LOGGER = get_logger()
  79
  80
  81def generate_client_secret() -> str:
  82    """Generate client secret with adequate length"""
  83    return generate_id(128)
  84
  85
  86def hash_refresh_token(raw: str) -> str:
  87    """Hash a refresh token for storage. Refresh tokens are long random values, so an unsalted
  88    SHA-256 is sufficient; a slow password hash would only make every refresh more expensive."""
  89    return sha256(raw.encode("utf-8")).hexdigest()
  90
  91
  92class ClientType(models.TextChoices):
  93    """Confidential clients are capable of maintaining the confidentiality
  94    of their credentials. Public clients are incapable."""
  95
  96    CONFIDENTIAL = "confidential", _("Confidential")
  97    PUBLIC = "public", _("Public")
  98
  99
 100class GrantType(models.TextChoices):
 101    """OAuth2 Grant types we support"""
 102
 103    AUTHORIZATION_CODE = GRANT_TYPE_AUTHORIZATION_CODE
 104    IMPLICIT = GRANT_TYPE_IMPLICIT
 105    HYBRID = GRANT_TYPE_HYBRID
 106    REFRESH_TOKEN = GRANT_TYPE_REFRESH_TOKEN
 107    CLIENT_CREDENTIALS = GRANT_TYPE_CLIENT_CREDENTIALS
 108    PASSWORD = GRANT_TYPE_PASSWORD
 109    DEVICE_CODE = GRANT_TYPE_DEVICE_CODE
 110    TOKEN_EXCHANGE = GRANT_TYPE_TOKEN_EXCHANGE
 111
 112
 113class ResponseMode(models.TextChoices):
 114    """https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#OAuth.Post"""
 115
 116    QUERY = "query"
 117    FRAGMENT = "fragment"
 118    FORM_POST = "form_post"
 119
 120
 121class IssuerMode(models.TextChoices):
 122    """Configure how the `iss` field is created."""
 123
 124    GLOBAL = "global", _("Same identifier is used for all providers")
 125    PER_PROVIDER = (
 126        "per_provider",
 127        _("Each provider has a different issuer, based on the application slug."),
 128    )
 129
 130
 131class RedirectURIMatchingMode(models.TextChoices):
 132    STRICT = "strict", _("Strict URL comparison")
 133    REGEX = "regex", _("Regular Expression URL matching")
 134
 135
 136class RedirectURIType(models.TextChoices):
 137    AUTHORIZATION = "authorization", _("Authorization")
 138    LOGOUT = "logout", _("Logout")
 139
 140
 141class OAuth2LogoutMethod(models.TextChoices):
 142    """OAuth2/OIDC Logout methods"""
 143
 144    BACKCHANNEL = "backchannel", _("Back-channel")
 145    FRONTCHANNEL = "frontchannel", _("Front-channel")
 146
 147
 148@dataclass
 149class RedirectURI:
 150    """A single redirect URI entry"""
 151
 152    matching_mode: RedirectURIMatchingMode
 153    url: str
 154    redirect_uri_type: RedirectURIType = RedirectURIType.AUTHORIZATION
 155
 156
 157class ResponseTypes(models.TextChoices):
 158    """Response Type required by the client."""
 159
 160    CODE = "code", _("code (Authorization Code Flow)")
 161    ID_TOKEN = "id_token", _("id_token (Implicit Flow)")
 162    ID_TOKEN_TOKEN = "id_token token", _("id_token token (Implicit Flow)")
 163    CODE_TOKEN = "code token", _("code token (Hybrid Flow)")
 164    CODE_ID_TOKEN = "code id_token", _("code id_token (Hybrid Flow)")
 165    CODE_ID_TOKEN_TOKEN = "code id_token token", _("code id_token token (Hybrid Flow)")
 166
 167
 168class JWTAlgorithms(models.TextChoices):
 169    """Algorithm used to sign the JWT Token"""
 170
 171    HS256 = "HS256", _("HS256 (Symmetric Encryption)")
 172    RS256 = "RS256", _("RS256 (Asymmetric Encryption)")
 173    ES256 = "ES256", _("ES256 (Asymmetric Encryption)")
 174    ES384 = "ES384", _("ES384 (Asymmetric Encryption)")
 175    ES512 = "ES512", _("ES512 (Asymmetric Encryption)")
 176    EDDSA = "EdDSA", _("EdDSA (Asymmetric Encryption)")
 177    MLDSA44 = "ML-DSA-44", _("ML-DSA-44 (Post-quantum, Asymmetric Encryption)")
 178    MLDSA65 = "ML-DSA-65", _("ML-DSA-65 (Post-quantum, Asymmetric Encryption)")
 179    MLDSA87 = "ML-DSA-87", _("ML-DSA-87 (Post-quantum, Asymmetric Encryption)")
 180
 181    @classmethod
 182    def from_private_key(cls, private_key: PrivateKeyTypes | None) -> str:
 183        return cls.from_public_key(private_key.public_key() if private_key else None)
 184
 185    @classmethod
 186    def from_public_key(cls, public_key: PublicKeyTypes | None) -> str:
 187        if isinstance(public_key, MLDSAKey):
 188            return cls(MLDSAAlgorithm.algorithm_for_key(public_key))
 189        if isinstance(public_key, RSAPublicKey):
 190            return cls.RS256
 191        if isinstance(public_key, EllipticCurvePublicKey):
 192            curve = public_key.curve
 193            if isinstance(curve, SECP256R1):
 194                return cls.ES256
 195            if isinstance(curve, SECP384R1):
 196                return cls.ES384
 197            if isinstance(curve, SECP521R1):
 198                return cls.ES512
 199        if isinstance(public_key, Ed25519PublicKey | Ed448PublicKey):
 200            return cls.EDDSA
 201        raise ValueError(f"Invalid key type: {type(public_key)}")
 202
 203
 204class ScopeMapping(PropertyMapping):
 205    """Map an OAuth Scope to users properties"""
 206
 207    expression_allowed_types = [dict]
 208
 209    scope_name = models.TextField(help_text=_("Scope used by the client"))
 210    description = models.TextField(
 211        blank=True,
 212        help_text=_(
 213            "Description shown to the user when consenting. "
 214            "If left empty, the user won't be informed."
 215        ),
 216    )
 217
 218    @property
 219    def component(self) -> str:
 220        return "ak-property-mapping-provider-scope-form"
 221
 222    @property
 223    def serializer(self) -> type[Serializer]:
 224        from authentik.providers.oauth2.api.scopes import ScopeMappingSerializer
 225
 226        return ScopeMappingSerializer
 227
 228    def __str__(self):
 229        return f"Scope Mapping {self.name} ({self.scope_name})"
 230
 231    class Meta:
 232        verbose_name = _("Scope Mapping")
 233        verbose_name_plural = _("Scope Mappings")
 234
 235
 236class OAuth2Provider(WebfingerProvider, Provider):
 237    """OAuth2 Provider for generic OAuth and OpenID Connect Applications."""
 238
 239    client_type = models.CharField(
 240        max_length=30,
 241        choices=ClientType.choices,
 242        default=ClientType.CONFIDENTIAL,
 243        verbose_name=_("Client Type"),
 244        help_text=_(
 245            "Confidential clients are capable of maintaining the confidentiality "
 246            "of their credentials. Public clients are incapable"
 247        ),
 248    )
 249    grant_types = ArrayField(models.TextField(choices=GrantType.choices), default=list)
 250    client_id = models.CharField(
 251        max_length=255,
 252        unique=True,
 253        verbose_name=_("Client ID"),
 254        default=generate_id,
 255    )
 256    client_secret = models.CharField(
 257        max_length=255,
 258        blank=True,
 259        verbose_name=_("Client Secret"),
 260        default=generate_client_secret,
 261    )
 262    _redirect_uris = models.JSONField(
 263        default=list,
 264        verbose_name=_("Redirect URIs"),
 265    )
 266    logout_uri = models.TextField(
 267        validators=[DomainlessURLValidator(schemes=("http", "https"))],
 268        verbose_name=_("Logout URI"),
 269        blank=True,
 270    )
 271    logout_method = models.TextField(
 272        choices=OAuth2LogoutMethod.choices,
 273        default=OAuth2LogoutMethod.BACKCHANNEL,
 274        verbose_name=_("Logout Method"),
 275        help_text=_(
 276            "Backchannel logs out with server to server calls. "
 277            "Frontchannel uses iframes in your browser"
 278        ),
 279    )
 280    include_claims_in_id_token = models.BooleanField(
 281        default=True,
 282        verbose_name=_("Include claims in id_token"),
 283        help_text=_(
 284            "Include User claims from scopes in the id_token, for applications "
 285            "that don't access the userinfo endpoint."
 286        ),
 287    )
 288
 289    access_code_validity = models.TextField(
 290        default="minutes=1",
 291        validators=[timedelta_string_validator],
 292        help_text=_(
 293            "Access codes not valid on or after current time + this value "
 294            "(Format: hours=1;minutes=2;seconds=3)."
 295        ),
 296    )
 297    access_token_validity = models.TextField(
 298        default="hours=1",
 299        validators=[timedelta_string_validator],
 300        help_text=_(
 301            "Tokens not valid on or after current time + this value "
 302            "(Format: hours=1;minutes=2;seconds=3)."
 303        ),
 304    )
 305    refresh_token_validity = models.TextField(
 306        default="days=30",
 307        validators=[timedelta_string_validator],
 308        help_text=_(
 309            "Tokens not valid on or after current time + this value "
 310            "(Format: hours=1;minutes=2;seconds=3)."
 311        ),
 312    )
 313    refresh_token_threshold = models.TextField(
 314        default="seconds=0",
 315        validators=[timedelta_string_validator],
 316        help_text=_(
 317            "When refreshing a token, if the refresh token is valid for less than "
 318            "this duration, it will be renewed. "
 319            "When set to seconds=0, token will always be renewed. "
 320            "(Format: hours=1;minutes=2;seconds=3)."
 321        ),
 322    )
 323    refresh_token_revoke_family_on_reuse = models.BooleanField(
 324        default=True,
 325        db_default=True,
 326        help_text=_(
 327            "When a refresh token which has already been rotated is used again, revoke all "
 328            "refresh and access tokens issued from the same authorization. Reuse indicates "
 329            "that the token may have been stolen."
 330        ),
 331    )
 332    refresh_token_reuse_grace_period = models.TextField(
 333        default="seconds=30",
 334        db_default="seconds=30",
 335        validators=[timedelta_string_validator],
 336        help_text=_(
 337            "Allow the most recently rotated refresh token to be used again for this duration "
 338            "without revoking its family, for clients which retry or send concurrent refresh "
 339            "requests. Only applies when revoking the family on reuse is enabled. "
 340            "(Format: hours=1;minutes=2;seconds=3)."
 341        ),
 342    )
 343
 344    sub_mode = models.TextField(
 345        choices=SubModes.choices,
 346        default=SubModes.HASHED_USER_ID,
 347        help_text=_(
 348            "Configure what data should be used as unique User Identifier. For most cases, "
 349            "the default should be fine."
 350        ),
 351    )
 352    issuer_mode = models.TextField(
 353        choices=IssuerMode.choices,
 354        default=IssuerMode.PER_PROVIDER,
 355        help_text=_("Configure how the issuer field of the ID Token should be filled."),
 356    )
 357
 358    signing_key = models.ForeignKey(
 359        CertificateKeyPair,
 360        verbose_name=_("Signing Key"),
 361        on_delete=models.SET_NULL,
 362        null=True,
 363        help_text=_("Key used to sign the tokens."),
 364        related_name="oauth2provider_signing_key_set",
 365    )
 366    encryption_key = models.ForeignKey(
 367        CertificateKeyPair,
 368        verbose_name=_("Encryption Key"),
 369        on_delete=models.SET_NULL,
 370        null=True,
 371        help_text=_(
 372            "Key used to encrypt the tokens. When set, "
 373            "tokens will be encrypted and returned as JWEs."
 374        ),
 375        related_name="oauth2provider_encryption_key_set",
 376    )
 377
 378    jwt_federation_sources = models.ManyToManyField(
 379        OAuthSource,
 380        verbose_name=_(
 381            "Any JWT signed by the JWK of the selected source can be used to authenticate."
 382        ),
 383        related_name="oauth2_providers",
 384        default=None,
 385        blank=True,
 386        through="OAuth2ProviderJWTFederationSource",
 387    )
 388    jwt_federation_providers = models.ManyToManyField(
 389        "OAuth2Provider", blank=True, default=None, through="OAuth2ProviderJWTFederationProvider"
 390    )
 391
 392    @cached_property
 393    def jwt_key(self) -> tuple[str | PrivateKeyTypes, str]:
 394        """Get either the configured certificate or the client secret"""
 395        if not self.signing_key:
 396            # No Certificate at all, assume HS256
 397            return self.client_secret, JWTAlgorithms.HS256
 398        key: CertificateKeyPair = self.signing_key
 399        private_key = key.private_key
 400        return private_key, JWTAlgorithms.from_private_key(private_key)
 401
 402    @cached_property
 403    def jwt_alg(self) -> str:
 404        """Get the signing algorithm without loading the private key for signing"""
 405        if not self.signing_key:
 406            return JWTAlgorithms.HS256
 407        return JWTAlgorithms.from_public_key(self.signing_key.public_key)
 408
 409    def get_issuer(self, request: HttpRequest) -> str | None:
 410        """Get issuer, based on request"""
 411        if self.issuer_mode == IssuerMode.GLOBAL:
 412            return request.build_absolute_uri(reverse("authentik_core:root-redirect"))
 413        try:
 414            url = reverse(
 415                "authentik_providers_oauth2:provider-root",
 416                kwargs={
 417                    "application_slug": self.application.slug,
 418                },
 419            )
 420            return request.build_absolute_uri(url)
 421        except Provider.application.RelatedObjectDoesNotExist:
 422            return None
 423
 424    @property
 425    def redirect_uris(self) -> list[RedirectURI]:
 426        uris = []
 427        for entry in self._redirect_uris:
 428            uris.append(
 429                from_dict(
 430                    RedirectURI,
 431                    entry,
 432                    config=Config(
 433                        type_hooks={
 434                            RedirectURIMatchingMode: RedirectURIMatchingMode,
 435                            RedirectURIType: RedirectURIType,
 436                        }
 437                    ),
 438                )
 439            )
 440        return uris
 441
 442    @redirect_uris.setter
 443    def redirect_uris(self, value: list[RedirectURI]):
 444        cleansed = []
 445        for entry in value:
 446            cleansed.append(asdict(entry))
 447        self._redirect_uris = cleansed
 448
 449    @property
 450    def authorization_redirect_uris(self) -> list[RedirectURI]:
 451        return [
 452            uri
 453            for uri in self.redirect_uris
 454            if uri.redirect_uri_type == RedirectURIType.AUTHORIZATION
 455        ]
 456
 457    @property
 458    def post_logout_redirect_uris(self) -> list[RedirectURI]:
 459        return [
 460            uri for uri in self.redirect_uris if uri.redirect_uri_type == RedirectURIType.LOGOUT
 461        ]
 462
 463    @property
 464    def launch_url(self) -> str | None:
 465        """Guess launch_url based on first redirect_uri"""
 466        redirects = self.authorization_redirect_uris
 467        if len(redirects) < 1:
 468            return None
 469        main_url = redirects[0].url
 470        try:
 471            launch_url = urlparse(main_url)._replace(path="")
 472            return urlunparse(launch_url)
 473        except ValueError as exc:
 474            LOGGER.warning("Failed to format launch url", exc=exc)
 475            return None
 476
 477    @property
 478    def icon_url(self) -> str | None:
 479        return static("authentik/sources/openidconnect/light.svg")
 480
 481    @property
 482    def component(self) -> str:
 483        return "ak-provider-oauth2-form"
 484
 485    @property
 486    def serializer(self) -> type[Serializer]:
 487        from authentik.providers.oauth2.api.providers import OAuth2ProviderSerializer
 488
 489        return OAuth2ProviderSerializer
 490
 491    def __str__(self):
 492        return f"OAuth2 Provider {self.name}"
 493
 494    @active_tracer().instrument()
 495    def encode(self, payload: dict[str, Any], jwt_type: str | None = None) -> str:
 496        """Represent the ID Token as a JSON Web Token (JWT).
 497
 498        :param payload The payload to encode into the JWT
 499        :param jwt_type The type of the JWT. This will be put in the JWT header using the `typ`
 500            parameter. See RFC7515 Section 4.1.9. If not set fallback to the default of `JWT`.
 501        """
 502        headers = {}
 503        if self.signing_key:
 504            headers["kid"] = self.signing_key.kid
 505        if jwt_type is not None:
 506            headers["typ"] = jwt_type
 507        key, alg = self.jwt_key
 508        encoded = encode(payload, key, algorithm=alg, headers=headers)
 509        if self.encryption_key:
 510            return self.encrypt(encoded)
 511        return encoded
 512
 513    def encrypt(self, raw: str) -> str:
 514        """Encrypt JWT"""
 515        key = JWK.from_pem(self.encryption_key.certificate_data.encode())
 516        jwe = JWE(
 517            raw,
 518            json_encode(
 519                {
 520                    "alg": "RSA-OAEP-256",
 521                    "enc": "A256CBC-HS512",
 522                    "typ": "JWE",
 523                    "kid": self.encryption_key.kid,
 524                }
 525            ),
 526        )
 527        jwe.add_recipient(key)
 528        return jwe.serialize(compact=True)
 529
 530    def webfinger(self, resource: str, request: HttpRequest):
 531        return {
 532            "subject": resource,
 533            "links": [
 534                {
 535                    "rel": "http://openid.net/specs/connect/1.0/issuer",
 536                    "href": request.build_absolute_uri(
 537                        reverse(
 538                            "authentik_providers_oauth2:provider-root",
 539                            kwargs={
 540                                "application_slug": self.application.slug,
 541                            },
 542                        )
 543                    ),
 544                },
 545            ],
 546        }
 547
 548    class Meta:
 549        verbose_name = _("OAuth2/OpenID Provider")
 550        verbose_name_plural = _("OAuth2/OpenID Providers")
 551
 552
 553class OAuth2ProviderJWTFederationSource(SimpleThroughModel):
 554    oauth2_provider = models.ForeignKey(
 555        OAuth2Provider, on_delete=models.CASCADE, db_column="oauth2provider_id"
 556    )
 557    oauth_source = models.ForeignKey(
 558        OAuthSource, on_delete=models.CASCADE, db_column="oauthsource_id"
 559    )
 560
 561    class Meta:
 562        db_table = "authentik_providers_oauth2_oauth2provider_jwt_federation_so2b48"
 563        unique_together = (("oauth2_provider", "oauth_source"),)
 564        verbose_name = _("OAuth2 Provider JWT Federation Source")
 565        verbose_name_plural = _("OAuth2 Provider JWT Federation Sources")
 566
 567    def __str__(self):
 568        return (
 569            f"OAuth2ProviderJWTFederationSource for OAuth2Provider {self.oauth2_provider_id} "
 570            f"and OauthSource {self.oauth_source_id}."
 571        )
 572
 573
 574class OAuth2ProviderJWTFederationProvider(SimpleThroughModel):
 575    oauth2_provider = models.ForeignKey(
 576        OAuth2Provider,
 577        on_delete=models.CASCADE,
 578        related_name="jwt_federation_provider_m2m_objects",
 579        db_column="from_oauth2provider_id",
 580    )
 581    jwt_federation_provider = models.ForeignKey(
 582        OAuth2Provider,
 583        on_delete=models.CASCADE,
 584        related_name="oauth2_provider_m2m_objects",
 585        db_column="to_oauth2provider_id",
 586    )
 587
 588    class Meta:
 589        db_table = "authentik_providers_oauth2_oauth2provider_jwt_federation_pr9002"
 590        unique_together = (("oauth2_provider", "jwt_federation_provider"),)
 591        verbose_name = _("OAuth2 Provider JWT Federation Provider")
 592        verbose_name_plural = _("OAuth2 Provider JWT Federation Providers")
 593
 594    def __str__(self):
 595        return (
 596            f"OAuth2ProviderJWTFederationProvider for OAuth2Provider {self.oauth2_provider_id} "
 597            f"and JWTFederationProvider {self.jwt_federation_provider_id}."
 598        )
 599
 600
 601class BaseGrantModel(models.Model):
 602    """Base Model for all grants"""
 603
 604    provider = models.ForeignKey(OAuth2Provider, on_delete=models.CASCADE)
 605    user = models.ForeignKey(User, verbose_name=_("User"), on_delete=models.CASCADE)
 606    revoked = models.BooleanField(default=False)
 607    _scope = models.TextField(default="", verbose_name=_("Scopes"))
 608    auth_time = models.DateTimeField(verbose_name="Authentication time")
 609    session = models.ForeignKey(
 610        AuthenticatedSession, null=True, on_delete=models.CASCADE, default=None
 611    )
 612    # RFC 8693 §4.1 delegation: set when this grant was obtained via a token-exchange
 613    # request presenting an `actor_token` (e.g. an Actor's own API token) alongside the
 614    # `subject_token` -- `user` above stays the subject (unchanged), `actor` records who
 615    # is actually exercising the token, and is mirrored into the issued token's `act` claim.
 616    actor = models.ForeignKey(
 617        User,
 618        on_delete=models.SET_NULL,
 619        related_name="actor_for_%(class)ss",
 620        null=True,
 621        blank=True,
 622        default=None,
 623    )
 624
 625    class Meta:
 626        abstract = True
 627
 628    @property
 629    def scope(self) -> list[str]:
 630        """Return scopes as list of strings"""
 631        return self._scope.split()
 632
 633    @scope.setter
 634    def scope(self, value):
 635        self._scope = " ".join(value)
 636
 637
 638class AuthorizationCode(InternallyManagedMixin, SerializerModel, ExpiringModel, BaseGrantModel):
 639    """OAuth2 Authorization Code"""
 640
 641    code = models.CharField(max_length=255, unique=True, verbose_name=_("Code"))
 642    nonce = models.TextField(null=True, default=None, verbose_name=_("Nonce"))
 643    code_challenge = models.CharField(max_length=255, null=True, verbose_name=_("Code Challenge"))
 644    code_challenge_method = models.CharField(
 645        max_length=255, null=True, verbose_name=_("Code Challenge Method")
 646    )
 647    dpop_jkt = models.CharField(
 648        max_length=255, null=True, default=None, verbose_name=_("DPoP JWK Thumbprint")
 649    )
 650
 651    class Meta:
 652        verbose_name = _("Authorization Code")
 653        verbose_name_plural = _("Authorization Codes")
 654        indexes = ExpiringModel.Meta.indexes
 655
 656    def __str__(self):
 657        return f"Authorization code for {self.provider_id} for user {self.user_id}"
 658
 659    @property
 660    def serializer(self) -> Serializer:
 661        from authentik.providers.oauth2.api.tokens import ExpiringBaseGrantModelSerializer
 662
 663        return ExpiringBaseGrantModelSerializer
 664
 665    @property
 666    def c_hash(self):
 667        """https://openid.net/specs/openid-connect-core-1_0.html#IDToken"""
 668        hashed_code = sha256(self.code.encode("ascii")).hexdigest().encode("ascii")
 669        return (
 670            base64.urlsafe_b64encode(binascii.unhexlify(hashed_code[: len(hashed_code) // 2]))
 671            .rstrip(b"=")
 672            .decode("ascii")
 673        )
 674
 675
 676class AccessToken(InternallyManagedMixin, SerializerModel, ExpiringModel, BaseGrantModel):
 677    """OAuth2 access token, non-opaque using a JWT as identifier"""
 678
 679    token = models.TextField()
 680    _id_token = models.TextField()
 681    # Family of the refresh token issued alongside this token, so the access tokens are revoked
 682    # together with the refresh tokens when reuse is detected
 683    family = models.UUIDField(null=True, default=None)
 684
 685    class Meta:
 686        indexes = ExpiringModel.Meta.indexes + [
 687            HashIndex(fields=["token"]),
 688            # Most access tokens have no family (no refresh token was issued), so only index the
 689            # ones that do. This keeps the index small and cheap to maintain on insert
 690            models.Index(
 691                fields=["family"],
 692                name="authentik_p_at_family_idx",
 693                condition=Q(family__isnull=False),
 694            ),
 695        ]
 696        verbose_name = _("OAuth2 Access Token")
 697        verbose_name_plural = _("OAuth2 Access Tokens")
 698
 699    def __str__(self):
 700        return f"Access Token for {self.provider_id} for user {self.user_id}"
 701
 702    @property
 703    def id_token(self) -> IDToken:
 704        """Load ID Token from json"""
 705        from authentik.providers.oauth2.id_token import IDToken
 706
 707        raw_token = json.loads(self._id_token)
 708        return from_dict(IDToken, raw_token)
 709
 710    @id_token.setter
 711    def id_token(self, value: IDToken):
 712        self.token = value.to_access_token(self.provider, self)
 713        self._id_token = json.dumps(asdict(value))
 714
 715    @property
 716    def at_hash(self):
 717        """Get hashed access_token"""
 718        hashed_access_token = sha256(self.token.encode("ascii")).hexdigest().encode("ascii")
 719        return (
 720            base64.urlsafe_b64encode(
 721                binascii.unhexlify(hashed_access_token[: len(hashed_access_token) // 2])
 722            )
 723            .rstrip(b"=")
 724            .decode("ascii")
 725        )
 726
 727    @property
 728    def serializer(self) -> Serializer:
 729        from authentik.providers.oauth2.api.tokens import TokenModelSerializer
 730
 731        return TokenModelSerializer
 732
 733
 734class RefreshToken(InternallyManagedMixin, SerializerModel, ExpiringModel, BaseGrantModel):
 735    """OAuth2 Refresh Token, opaque. Tokens are looked up by their hash, see `token`."""
 736
 737    # Plaintext token column from before refresh tokens were hashed at rest. It is still written,
 738    # as the previous authentik version looks tokens up by it: during a rolling upgrade or after
 739    # a rollback, that version must be able to find tokens issued by this one, and must never
 740    # find a token with no plaintext when it looks up a missing token (`token=None`). A future
 741    # release will stop writing it, then remove it. Until then, it is also the lookup fallback
 742    # for tokens issued by an older version, which have no hash.
 743    legacy_token = models.TextField(db_column="token", null=True, default=None)
 744    # Tokens issued by an older version have no hash until they are next saved
 745    token_hash = models.TextField(null=True, default=None)
 746    # All refresh tokens rotated from the same authorization share a family, so that reuse of a
 747    # rotated token can revoke the whole chain (RFC 9700 Section 4.14.2). Tokens issued by an
 748    # older version have no family until they are refreshed.
 749    family = models.UUIDField(null=True, default=uuid4)
 750    rotated_at = models.DateTimeField(null=True, default=None)
 751    _id_token = models.TextField(verbose_name=_("ID Token"))
 752    dpop_jkt = models.CharField(
 753        max_length=255, null=True, default=None, verbose_name=_("DPoP JWK Thumbprint")
 754    )
 755    # Shadow the `session` field from `BaseGrantModel` as we want refresh tokens to persist even
 756    # when the session is terminated.
 757    session = models.ForeignKey(
 758        AuthenticatedSession, null=True, on_delete=models.SET_DEFAULT, default=None
 759    )
 760
 761    _raw_token: str | None = None
 762
 763    class Meta:
 764        indexes = ExpiringModel.Meta.indexes + [
 765            HashIndex(fields=["legacy_token"]),
 766            HashIndex(fields=["token_hash"]),
 767            # Tokens issued by an older version have no family, only index the ones that do
 768            models.Index(
 769                fields=["family"],
 770                name="authentik_p_rt_family_idx",
 771                condition=Q(family__isnull=False),
 772            ),
 773        ]
 774        verbose_name = _("OAuth2 Refresh Token")
 775        verbose_name_plural = _("OAuth2 Refresh Tokens")
 776
 777    def __str__(self):
 778        return f"Refresh Token for {self.provider_id} for user {self.user_id}"
 779
 780    def save(self, *args, **kwargs):
 781        if not self.token_hash:
 782            if self.legacy_token:
 783                # Issued by an older version, hash it so lookups don't need the fallback
 784                self.token_hash = hash_refresh_token(self.legacy_token)
 785            else:
 786                self.token = generate_client_secret()
 787        return super().save(*args, **kwargs)
 788
 789    @property
 790    def token(self) -> str | None:
 791        """The raw token value. Only set on a token created in this process (to return it to
 792        the client), never on one loaded from the database, which is looked up by its hash."""
 793        return self._raw_token
 794
 795    @token.setter
 796    def token(self, value: str | None):
 797        self._raw_token = value
 798        self.token_hash = hash_refresh_token(value) if value else None
 799        # Still written for the previous version, see `legacy_token`
 800        self.legacy_token = value
 801
 802    @staticmethod
 803    def token_query(raw: str | None) -> Q:
 804        """Query matching the refresh token with the raw value `raw`"""
 805        if not raw:
 806            # Never fall through to `legacy_token=None`, which matches every hashed token
 807            return Q(pk__in=[])
 808        return Q(token_hash=hash_refresh_token(raw)) | Q(legacy_token=raw)
 809
 810    @staticmethod
 811    def lock_family(family: UUID) -> None:
 812        """Lock the family `family` until the current transaction ends. Refreshing a token
 813        (which may issue tokens of its family), revoking a family on reuse and revoking it via
 814        RFC 7009 hold this lock while doing so.
 815
 816        Revoking a family is an UPDATE of its tokens, and an UPDATE can't see a token inserted
 817        by a concurrent transaction which hasn't committed yet. Without the lock, a token issued
 818        concurrently (by a rotation, or within the reuse grace period) would escape the
 819        revocation. With it, the revocation waits until that token is committed, or the request
 820        issuing it waits until the revocation is committed and then sees it.
 821
 822        Deleting tokens by user, session or expiry doesn't take the lock. A refresh racing with
 823        such a deletion either fails because its token is gone, or issues tokens which the
 824        deletion doesn't see."""
 825        if not family:
 826            # Every token without a family would share this lock
 827            raise ValueError("Tokens without a family can't be locked")
 828        if not connection.in_atomic_block:
 829            # Outside of a transaction the lock would be released immediately
 830            raise TransactionManagementError(
 831                "Refresh token families can only be locked in a transaction"
 832            )
 833        with connection.cursor() as cursor:
 834            cursor.execute(
 835                "SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))",
 836                [f"authentik_providers_oauth2.refreshtoken.family:{family}"],
 837            )
 838
 839    def start_family(self) -> None:
 840        """Start a family for a token issued before refresh token families existed, and hash it.
 841        Concurrent requests presenting the same token may race here, so only the first one sets
 842        the family, and all of them use that one. Raises `DoesNotExist` when the token has been
 843        deleted.
 844
 845        Includes expired tokens, so that a token which expired since it was loaded still gets
 846        its family: `refresh_from_db` would load it anyway, and a caller filtering by its unset
 847        family would match every token without a family."""
 848        if self.family:
 849            return
 850        update: dict[str, Any] = {"family": uuid4()}
 851        if not self.token_hash and self.legacy_token:
 852            update["token_hash"] = hash_refresh_token(self.legacy_token)
 853        RefreshToken.objects.including_expired().filter(pk=self.pk, family__isnull=True).update(
 854            **update
 855        )
 856        self.refresh_from_db(fields=["family", "token_hash"])
 857
 858    def consume(self, now: datetime) -> bool:
 859        """Rotate this token: mark it as revoked, keeping it so its reuse can be detected.
 860
 861        Called with the family locked (see `lock_family`). It is still a single conditional
 862        update, so that it fails rather than issuing a second successor when the token was
 863        changed by something which doesn't hold the lock (such as the previous version during a
 864        rolling upgrade). Then it returns False, and the request must be treated as reuse."""
 865        consumed = (
 866            RefreshToken.objects.including_expired()
 867            .filter(pk=self.pk, revoked=False)
 868            .update(revoked=True, rotated_at=now)
 869            == 1
 870        )
 871        if consumed:
 872            self.revoked = True
 873            self.rotated_at = now
 874        return consumed
 875
 876    def claim_reuse_grace(self, rotated_after: datetime) -> bool:
 877        """Check whether this rotated token may be used again within the reuse grace period,
 878        because it is the most recently rotated token of a family which still has an active
 879        token, and it was rotated after `rotated_after`.
 880
 881        Called with the family locked (see `lock_family`), so that the token issued within the
 882        grace period can't escape a concurrent revocation of the family. The rotation time is
 883        kept, so that repeated reuse can't extend the grace period."""
 884        if not self.family:
 885            # Never compare with `family=None`, which would match every token without a family
 886            return False
 887        family = RefreshToken.objects.filter(family=OuterRef("family"))
 888        return (
 889            RefreshToken.objects.including_expired()
 890            .filter(
 891                pk=self.pk,
 892                revoked=True,
 893                rotated_at__gt=rotated_after,
 894            )
 895            .filter(
 896                # Another token was rotated since, so this one isn't the most recently rotated
 897                ~Exists(family.filter(rotated_at__gt=OuterRef("rotated_at"))),
 898                # The family has been revoked (or its active token revoked via RFC 7009)
 899                Exists(family.filter(revoked=False)),
 900            )
 901            .update(rotated_at=F("rotated_at"))
 902            == 1
 903        )
 904
 905    def revoke_family(self) -> None:
 906        """Revoke all refresh and access tokens of this token's family, when reuse of a rotated
 907        token is detected. The refresh tokens are kept, so that their reuse is still detected."""
 908        self.revoked = True
 909        with transaction.atomic():
 910            if not self.family:
 911                # Never filter by `family=None`, which would match every token without a family
 912                RefreshToken.objects.filter(pk=self.pk).update(revoked=True)
 913                return
 914            self.lock_family(self.family)
 915            RefreshToken.objects.including_expired().filter(
 916                family=self.family, revoked=False
 917            ).update(revoked=True)
 918            # Deleted rather than marked as revoked: not everything which accepts access tokens
 919            # checks `revoked` (API authentication, DCR, the endpoint agent, JWT federation)
 920            AccessToken.objects.including_expired().filter(family=self.family).delete()
 921
 922    def delete_family(self) -> None:
 923        """Delete all refresh and access tokens of this token's family, when it is revoked by
 924        the client (RFC 7009 Section 2.1). This includes the other tokens issued for retries
 925        within the reuse grace period, which the client may not know about."""
 926        with transaction.atomic():
 927            if not self.family:
 928                # Issued before refresh token families existed. Start its family like a refresh
 929                # does, so that a concurrent refresh of this token (which may already have
 930                # started it, and be issuing tokens of it) is serialized with this through the
 931                # family's lock
 932                try:
 933                    self.start_family()
 934                except RefreshToken.DoesNotExist:
 935                    return
 936            if not self.family:
 937                # Never filter by `family=None`, which would match every token without a family
 938                return
 939            self.lock_family(self.family)
 940            AccessToken.objects.including_expired().filter(family=self.family).delete()
 941            RefreshToken.objects.including_expired().filter(family=self.family).delete()
 942
 943    @property
 944    def id_token(self) -> IDToken:
 945        """Load ID Token from json"""
 946        from authentik.providers.oauth2.id_token import IDToken
 947
 948        raw_token = json.loads(self._id_token)
 949        return from_dict(IDToken, raw_token)
 950
 951    @id_token.setter
 952    def id_token(self, value: IDToken):
 953        self._id_token = json.dumps(asdict(value))
 954
 955    @property
 956    def serializer(self) -> Serializer:
 957        from authentik.providers.oauth2.api.tokens import TokenModelSerializer
 958
 959        return TokenModelSerializer
 960
 961
 962class OAuth2SessionLogin(InternallyManagedMixin, models.Model):
 963    """Record of providers the user has logged in to this session. required for
 964    front/backchannel logout because tokens can expire before the RP's session ends.
 965
 966    https://openid.net/specs/openid-connect-frontchannel-1_0.html#OPLogout
 967    https://openid.net/specs/openid-connect-backchannel-1_0.html#Tracking"""
 968
 969    session = models.ForeignKey(AuthenticatedSession, on_delete=models.CASCADE)
 970    provider = models.ForeignKey(OAuth2Provider, on_delete=models.CASCADE)
 971    # Stored as issued to the RP, as the issuer can't be resolved without a request and the
 972    # provider's `sub_mode` might change during the lifetime of the session.
 973    iss = models.TextField()
 974    sub = models.TextField()
 975
 976    class Meta:
 977        verbose_name = _("OAuth2 Session Login")
 978        verbose_name_plural = _("OAuth2 Session Logins")
 979        constraints = [
 980            models.UniqueConstraint(
 981                fields=("session", "provider"), name="oauth2_session_login_unique"
 982            ),
 983        ]
 984
 985    def __str__(self):
 986        return f"Session Login for {self.provider_id} for session {self.session_id}"
 987
 988    @classmethod
 989    def record(cls, token: BaseGrantModel, id_token: IDToken) -> None:
 990        """Remember that the provider of `token` has been issued `id_token` for its session"""
 991        if not token.session_id:
 992            return
 993        cls.objects.update_or_create(
 994            session_id=token.session_id,
 995            provider=token.provider,
 996            defaults={"iss": id_token.iss, "sub": id_token.sub},
 997        )
 998
 999
1000class DeviceToken(InternallyManagedMixin, ExpiringModel):
1001    """Temporary device token for OAuth device flow"""
1002
1003    user = models.ForeignKey(
1004        "authentik_core.User", default=None, on_delete=models.CASCADE, null=True
1005    )
1006    provider = models.ForeignKey(OAuth2Provider, on_delete=models.CASCADE)
1007    device_code = models.TextField(default=generate_key)
1008    user_code = models.TextField(default=generate_code_fixed_length)
1009    _scope = models.TextField(default="", verbose_name=_("Scopes"))
1010    dpop_jkt = models.CharField(
1011        max_length=255, null=True, default=None, verbose_name=_("DPoP JWK Thumbprint")
1012    )
1013    session = models.ForeignKey(
1014        AuthenticatedSession, null=True, on_delete=models.SET_DEFAULT, default=None
1015    )
1016
1017    @property
1018    def scope(self) -> list[str]:
1019        """Return scopes as list of strings"""
1020        return self._scope.split()
1021
1022    @scope.setter
1023    def scope(self, value):
1024        self._scope = " ".join(value)
1025
1026    class Meta:
1027        verbose_name = _("Device Token")
1028        verbose_name_plural = _("Device Tokens")
1029        indexes = ExpiringModel.Meta.indexes
1030
1031    def __str__(self):
1032        return f"Device Token for {self.provider_id}"
1033
1034
1035class OAuth2DynamicClientRegistration(SerializerModel, PolicyBindingModel):
1036    """Configuration for Dynamic Client Registration (RFC 7591) on an OAuth2Provider."""
1037
1038    provider = models.OneToOneField(
1039        OAuth2Provider,
1040        on_delete=models.CASCADE,
1041        related_name="dcr_configuration",
1042        verbose_name=_("Provider"),
1043    )
1044
1045    default_application_group = models.TextField(
1046        blank=True,
1047        default="",
1048        verbose_name=_("Default application group"),
1049        help_text=_("Group to assign to automatically created applications."),
1050    )
1051
1052    override_authorization_flow = models.ForeignKey(
1053        "authentik_flows.Flow",
1054        on_delete=models.SET_NULL,
1055        null=True,
1056        blank=True,
1057        verbose_name=_("Override authorization flow"),
1058        help_text=_("Authorization flow applied to dynamically registered clients."),
1059        related_name="dcr_override_authorization_flow",
1060    )
1061    override_invalidation_flow = models.ForeignKey(
1062        "authentik_flows.Flow",
1063        on_delete=models.SET_NULL,
1064        null=True,
1065        blank=True,
1066        verbose_name=_("Override invalidation flow"),
1067        related_name="dcr_override_invalidation_flow",
1068    )
1069    override_property_mappings = models.ManyToManyField(
1070        ScopeMapping,
1071        blank=True,
1072        verbose_name=_("Override property mappings"),
1073        help_text=_("Scope mappings applied to dynamically registered clients."),
1074        through="DynamicClientRegistrationPropertyMapping",
1075    )
1076
1077    access_token_validity = models.TextField(
1078        default="hours=1",
1079        validators=[timedelta_string_validator],
1080        verbose_name=_("Access token validity"),
1081        help_text=_(
1082            "Maximum access token validity for registered clients "
1083            "(Format: hours=1;minutes=2;seconds=3)."
1084        ),
1085    )
1086    refresh_token_validity = models.TextField(
1087        default="days=30",
1088        validators=[timedelta_string_validator],
1089        verbose_name=_("Refresh token validity"),
1090        help_text=_(
1091            "Maximum refresh token validity for registered clients "
1092            "(Format: hours=1;minutes=2;seconds=3)."
1093        ),
1094    )
1095
1096    allowed_grant_types = ArrayField(
1097        models.TextField(choices=GrantType.choices),
1098        default=list,
1099        blank=True,
1100        verbose_name=_("Allowed grant types"),
1101        help_text=_("If empty, all grant types are allowed."),
1102    )
1103
1104    @property
1105    def serializer(self) -> type[Serializer]:
1106        from authentik.providers.oauth2.api.dcr import (
1107            OAuth2DynamicClientRegistrationSerializer,
1108        )
1109
1110        return OAuth2DynamicClientRegistrationSerializer
1111
1112    def __str__(self):
1113        return f"DCR Configuration for {self.provider_id}"
1114
1115    class Meta:
1116        verbose_name = _("OAuth2 Dynamic Client Registration")
1117        verbose_name_plural = _("OAuth2 Dynamic Client Registrations")
1118
1119
1120class DynamicClientRegistrationPropertyMapping(SimpleThroughModel):
1121    property_mapping = models.ForeignKey(ScopeMapping, on_delete=models.CASCADE)
1122    dynamic_client_registration = models.ForeignKey(
1123        OAuth2DynamicClientRegistration, on_delete=models.CASCADE
1124    )
1125
1126    class Meta:
1127        unique_together = (("property_mapping", "dynamic_client_registration"),)
1128        verbose_name = _("Dynamic Client Registration Property Mapping")
1129        verbose_name_plural = _("Dynamic Client Registration Property Mappings")
1130
1131    def __str__(self):
1132        return (
1133            "DynamicClientRegistrationPropertyMapping for DCR "
1134            f"{self.dynamic_client_registration_id} and PropertyMapping "
1135            f"{self.property_mapping_id}."
1136        )
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
def generate_client_secret() -> str:
82def generate_client_secret() -> str:
83    """Generate client secret with adequate length"""
84    return generate_id(128)

Generate client secret with adequate length

def hash_refresh_token(raw: str) -> str:
87def hash_refresh_token(raw: str) -> str:
88    """Hash a refresh token for storage. Refresh tokens are long random values, so an unsalted
89    SHA-256 is sufficient; a slow password hash would only make every refresh more expensive."""
90    return sha256(raw.encode("utf-8")).hexdigest()

Hash a refresh token for storage. Refresh tokens are long random values, so an unsalted SHA-256 is sufficient; a slow password hash would only make every refresh more expensive.

class ClientType(django.db.models.enums.TextChoices):
93class ClientType(models.TextChoices):
94    """Confidential clients are capable of maintaining the confidentiality
95    of their credentials. Public clients are incapable."""
96
97    CONFIDENTIAL = "confidential", _("Confidential")
98    PUBLIC = "public", _("Public")

Confidential clients are capable of maintaining the confidentiality of their credentials. Public clients are incapable.

CONFIDENTIAL = ClientType.CONFIDENTIAL
class GrantType(django.db.models.enums.TextChoices):
101class GrantType(models.TextChoices):
102    """OAuth2 Grant types we support"""
103
104    AUTHORIZATION_CODE = GRANT_TYPE_AUTHORIZATION_CODE
105    IMPLICIT = GRANT_TYPE_IMPLICIT
106    HYBRID = GRANT_TYPE_HYBRID
107    REFRESH_TOKEN = GRANT_TYPE_REFRESH_TOKEN
108    CLIENT_CREDENTIALS = GRANT_TYPE_CLIENT_CREDENTIALS
109    PASSWORD = GRANT_TYPE_PASSWORD
110    DEVICE_CODE = GRANT_TYPE_DEVICE_CODE
111    TOKEN_EXCHANGE = GRANT_TYPE_TOKEN_EXCHANGE

OAuth2 Grant types we support

AUTHORIZATION_CODE = GrantType.AUTHORIZATION_CODE
IMPLICIT = GrantType.IMPLICIT
HYBRID = GrantType.HYBRID
REFRESH_TOKEN = GrantType.REFRESH_TOKEN
CLIENT_CREDENTIALS = GrantType.CLIENT_CREDENTIALS
PASSWORD = GrantType.PASSWORD
DEVICE_CODE = GrantType.DEVICE_CODE
TOKEN_EXCHANGE = GrantType.TOKEN_EXCHANGE
class ResponseMode(django.db.models.enums.TextChoices):
114class ResponseMode(models.TextChoices):
115    """https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#OAuth.Post"""
116
117    QUERY = "query"
118    FRAGMENT = "fragment"
119    FORM_POST = "form_post"
class IssuerMode(django.db.models.enums.TextChoices):
122class IssuerMode(models.TextChoices):
123    """Configure how the `iss` field is created."""
124
125    GLOBAL = "global", _("Same identifier is used for all providers")
126    PER_PROVIDER = (
127        "per_provider",
128        _("Each provider has a different issuer, based on the application slug."),
129    )

Configure how the iss field is created.

PER_PROVIDER = IssuerMode.PER_PROVIDER
class RedirectURIMatchingMode(django.db.models.enums.TextChoices):
132class RedirectURIMatchingMode(models.TextChoices):
133    STRICT = "strict", _("Strict URL comparison")
134    REGEX = "regex", _("Regular Expression URL matching")

Class for creating enumerated string choices.

class RedirectURIType(django.db.models.enums.TextChoices):
137class RedirectURIType(models.TextChoices):
138    AUTHORIZATION = "authorization", _("Authorization")
139    LOGOUT = "logout", _("Logout")

Class for creating enumerated string choices.

class OAuth2LogoutMethod(django.db.models.enums.TextChoices):
142class OAuth2LogoutMethod(models.TextChoices):
143    """OAuth2/OIDC Logout methods"""
144
145    BACKCHANNEL = "backchannel", _("Back-channel")
146    FRONTCHANNEL = "frontchannel", _("Front-channel")

OAuth2/OIDC Logout methods

@dataclass
class RedirectURI:
149@dataclass
150class RedirectURI:
151    """A single redirect URI entry"""
152
153    matching_mode: RedirectURIMatchingMode
154    url: str
155    redirect_uri_type: RedirectURIType = RedirectURIType.AUTHORIZATION

A single redirect URI entry

RedirectURI( matching_mode: RedirectURIMatchingMode, url: str, redirect_uri_type: RedirectURIType = RedirectURIType.AUTHORIZATION)
matching_mode: RedirectURIMatchingMode
url: str
class ResponseTypes(django.db.models.enums.TextChoices):
158class ResponseTypes(models.TextChoices):
159    """Response Type required by the client."""
160
161    CODE = "code", _("code (Authorization Code Flow)")
162    ID_TOKEN = "id_token", _("id_token (Implicit Flow)")
163    ID_TOKEN_TOKEN = "id_token token", _("id_token token (Implicit Flow)")
164    CODE_TOKEN = "code token", _("code token (Hybrid Flow)")
165    CODE_ID_TOKEN = "code id_token", _("code id_token (Hybrid Flow)")
166    CODE_ID_TOKEN_TOKEN = "code id_token token", _("code id_token token (Hybrid Flow)")

Response Type required by the client.

ID_TOKEN_TOKEN = ResponseTypes.ID_TOKEN_TOKEN
CODE_ID_TOKEN = ResponseTypes.CODE_ID_TOKEN
CODE_ID_TOKEN_TOKEN = ResponseTypes.CODE_ID_TOKEN_TOKEN
class JWTAlgorithms(django.db.models.enums.TextChoices):
169class JWTAlgorithms(models.TextChoices):
170    """Algorithm used to sign the JWT Token"""
171
172    HS256 = "HS256", _("HS256 (Symmetric Encryption)")
173    RS256 = "RS256", _("RS256 (Asymmetric Encryption)")
174    ES256 = "ES256", _("ES256 (Asymmetric Encryption)")
175    ES384 = "ES384", _("ES384 (Asymmetric Encryption)")
176    ES512 = "ES512", _("ES512 (Asymmetric Encryption)")
177    EDDSA = "EdDSA", _("EdDSA (Asymmetric Encryption)")
178    MLDSA44 = "ML-DSA-44", _("ML-DSA-44 (Post-quantum, Asymmetric Encryption)")
179    MLDSA65 = "ML-DSA-65", _("ML-DSA-65 (Post-quantum, Asymmetric Encryption)")
180    MLDSA87 = "ML-DSA-87", _("ML-DSA-87 (Post-quantum, Asymmetric Encryption)")
181
182    @classmethod
183    def from_private_key(cls, private_key: PrivateKeyTypes | None) -> str:
184        return cls.from_public_key(private_key.public_key() if private_key else None)
185
186    @classmethod
187    def from_public_key(cls, public_key: PublicKeyTypes | None) -> str:
188        if isinstance(public_key, MLDSAKey):
189            return cls(MLDSAAlgorithm.algorithm_for_key(public_key))
190        if isinstance(public_key, RSAPublicKey):
191            return cls.RS256
192        if isinstance(public_key, EllipticCurvePublicKey):
193            curve = public_key.curve
194            if isinstance(curve, SECP256R1):
195                return cls.ES256
196            if isinstance(curve, SECP384R1):
197                return cls.ES384
198            if isinstance(curve, SECP521R1):
199                return cls.ES512
200        if isinstance(public_key, Ed25519PublicKey | Ed448PublicKey):
201            return cls.EDDSA
202        raise ValueError(f"Invalid key type: {type(public_key)}")

Algorithm used to sign the JWT Token

@classmethod
def from_private_key( cls, private_key: cryptography.hazmat.primitives.asymmetric.dh.DHPrivateKey | cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey | cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey | cryptography.hazmat.primitives.asymmetric.mldsa.MLDSA44PrivateKey | cryptography.hazmat.primitives.asymmetric.mldsa.MLDSA65PrivateKey | cryptography.hazmat.primitives.asymmetric.mldsa.MLDSA87PrivateKey | cryptography.hazmat.primitives.asymmetric.mlkem.MLKEM768PrivateKey | cryptography.hazmat.primitives.asymmetric.mlkem.MLKEM1024PrivateKey | cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey | cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey | cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey | cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey | cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey | None) -> str:
182    @classmethod
183    def from_private_key(cls, private_key: PrivateKeyTypes | None) -> str:
184        return cls.from_public_key(private_key.public_key() if private_key else None)
@classmethod
def from_public_key( cls, public_key: cryptography.hazmat.primitives.asymmetric.dh.DHPublicKey | cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicKey | cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey | cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey | cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey | cryptography.hazmat.primitives.asymmetric.ed448.Ed448PublicKey | cryptography.hazmat.primitives.asymmetric.mldsa.MLDSA44PublicKey | cryptography.hazmat.primitives.asymmetric.mldsa.MLDSA65PublicKey | cryptography.hazmat.primitives.asymmetric.mldsa.MLDSA87PublicKey | cryptography.hazmat.primitives.asymmetric.mlkem.MLKEM768PublicKey | cryptography.hazmat.primitives.asymmetric.mlkem.MLKEM1024PublicKey | cryptography.hazmat.primitives.asymmetric.x25519.X25519PublicKey | cryptography.hazmat.primitives.asymmetric.x448.X448PublicKey | None) -> str:
186    @classmethod
187    def from_public_key(cls, public_key: PublicKeyTypes | None) -> str:
188        if isinstance(public_key, MLDSAKey):
189            return cls(MLDSAAlgorithm.algorithm_for_key(public_key))
190        if isinstance(public_key, RSAPublicKey):
191            return cls.RS256
192        if isinstance(public_key, EllipticCurvePublicKey):
193            curve = public_key.curve
194            if isinstance(curve, SECP256R1):
195                return cls.ES256
196            if isinstance(curve, SECP384R1):
197                return cls.ES384
198            if isinstance(curve, SECP521R1):
199                return cls.ES512
200        if isinstance(public_key, Ed25519PublicKey | Ed448PublicKey):
201            return cls.EDDSA
202        raise ValueError(f"Invalid key type: {type(public_key)}")
class ScopeMapping(authentik.core.models.PropertyMapping):
205class ScopeMapping(PropertyMapping):
206    """Map an OAuth Scope to users properties"""
207
208    expression_allowed_types = [dict]
209
210    scope_name = models.TextField(help_text=_("Scope used by the client"))
211    description = models.TextField(
212        blank=True,
213        help_text=_(
214            "Description shown to the user when consenting. "
215            "If left empty, the user won't be informed."
216        ),
217    )
218
219    @property
220    def component(self) -> str:
221        return "ak-property-mapping-provider-scope-form"
222
223    @property
224    def serializer(self) -> type[Serializer]:
225        from authentik.providers.oauth2.api.scopes import ScopeMappingSerializer
226
227        return ScopeMappingSerializer
228
229    def __str__(self):
230        return f"Scope Mapping {self.name} ({self.scope_name})"
231
232    class Meta:
233        verbose_name = _("Scope Mapping")
234        verbose_name_plural = _("Scope Mappings")

Map an OAuth Scope to users properties

expression_allowed_types = [<class 'dict'>]
def scope_name(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def description(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

component: str
219    @property
220    def component(self) -> str:
221        return "ak-property-mapping-provider-scope-form"

Return component used to edit this object

serializer: type[rest_framework.serializers.Serializer]
223    @property
224    def serializer(self) -> type[Serializer]:
225        from authentik.providers.oauth2.api.scopes import ScopeMappingSerializer
226
227        return ScopeMappingSerializer

Get serializer for this model

propertymapping_ptr_id
propertymapping_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

oauth2dynamicclientregistration_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

dynamicclientregistrationpropertymapping_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class ScopeMapping.DoesNotExist(authentik.core.models.PropertyMapping.DoesNotExist):

The requested object does not exist

class ScopeMapping.MultipleObjectsReturned(authentik.core.models.PropertyMapping.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

237class OAuth2Provider(WebfingerProvider, Provider):
238    """OAuth2 Provider for generic OAuth and OpenID Connect Applications."""
239
240    client_type = models.CharField(
241        max_length=30,
242        choices=ClientType.choices,
243        default=ClientType.CONFIDENTIAL,
244        verbose_name=_("Client Type"),
245        help_text=_(
246            "Confidential clients are capable of maintaining the confidentiality "
247            "of their credentials. Public clients are incapable"
248        ),
249    )
250    grant_types = ArrayField(models.TextField(choices=GrantType.choices), default=list)
251    client_id = models.CharField(
252        max_length=255,
253        unique=True,
254        verbose_name=_("Client ID"),
255        default=generate_id,
256    )
257    client_secret = models.CharField(
258        max_length=255,
259        blank=True,
260        verbose_name=_("Client Secret"),
261        default=generate_client_secret,
262    )
263    _redirect_uris = models.JSONField(
264        default=list,
265        verbose_name=_("Redirect URIs"),
266    )
267    logout_uri = models.TextField(
268        validators=[DomainlessURLValidator(schemes=("http", "https"))],
269        verbose_name=_("Logout URI"),
270        blank=True,
271    )
272    logout_method = models.TextField(
273        choices=OAuth2LogoutMethod.choices,
274        default=OAuth2LogoutMethod.BACKCHANNEL,
275        verbose_name=_("Logout Method"),
276        help_text=_(
277            "Backchannel logs out with server to server calls. "
278            "Frontchannel uses iframes in your browser"
279        ),
280    )
281    include_claims_in_id_token = models.BooleanField(
282        default=True,
283        verbose_name=_("Include claims in id_token"),
284        help_text=_(
285            "Include User claims from scopes in the id_token, for applications "
286            "that don't access the userinfo endpoint."
287        ),
288    )
289
290    access_code_validity = models.TextField(
291        default="minutes=1",
292        validators=[timedelta_string_validator],
293        help_text=_(
294            "Access codes not valid on or after current time + this value "
295            "(Format: hours=1;minutes=2;seconds=3)."
296        ),
297    )
298    access_token_validity = models.TextField(
299        default="hours=1",
300        validators=[timedelta_string_validator],
301        help_text=_(
302            "Tokens not valid on or after current time + this value "
303            "(Format: hours=1;minutes=2;seconds=3)."
304        ),
305    )
306    refresh_token_validity = models.TextField(
307        default="days=30",
308        validators=[timedelta_string_validator],
309        help_text=_(
310            "Tokens not valid on or after current time + this value "
311            "(Format: hours=1;minutes=2;seconds=3)."
312        ),
313    )
314    refresh_token_threshold = models.TextField(
315        default="seconds=0",
316        validators=[timedelta_string_validator],
317        help_text=_(
318            "When refreshing a token, if the refresh token is valid for less than "
319            "this duration, it will be renewed. "
320            "When set to seconds=0, token will always be renewed. "
321            "(Format: hours=1;minutes=2;seconds=3)."
322        ),
323    )
324    refresh_token_revoke_family_on_reuse = models.BooleanField(
325        default=True,
326        db_default=True,
327        help_text=_(
328            "When a refresh token which has already been rotated is used again, revoke all "
329            "refresh and access tokens issued from the same authorization. Reuse indicates "
330            "that the token may have been stolen."
331        ),
332    )
333    refresh_token_reuse_grace_period = models.TextField(
334        default="seconds=30",
335        db_default="seconds=30",
336        validators=[timedelta_string_validator],
337        help_text=_(
338            "Allow the most recently rotated refresh token to be used again for this duration "
339            "without revoking its family, for clients which retry or send concurrent refresh "
340            "requests. Only applies when revoking the family on reuse is enabled. "
341            "(Format: hours=1;minutes=2;seconds=3)."
342        ),
343    )
344
345    sub_mode = models.TextField(
346        choices=SubModes.choices,
347        default=SubModes.HASHED_USER_ID,
348        help_text=_(
349            "Configure what data should be used as unique User Identifier. For most cases, "
350            "the default should be fine."
351        ),
352    )
353    issuer_mode = models.TextField(
354        choices=IssuerMode.choices,
355        default=IssuerMode.PER_PROVIDER,
356        help_text=_("Configure how the issuer field of the ID Token should be filled."),
357    )
358
359    signing_key = models.ForeignKey(
360        CertificateKeyPair,
361        verbose_name=_("Signing Key"),
362        on_delete=models.SET_NULL,
363        null=True,
364        help_text=_("Key used to sign the tokens."),
365        related_name="oauth2provider_signing_key_set",
366    )
367    encryption_key = models.ForeignKey(
368        CertificateKeyPair,
369        verbose_name=_("Encryption Key"),
370        on_delete=models.SET_NULL,
371        null=True,
372        help_text=_(
373            "Key used to encrypt the tokens. When set, "
374            "tokens will be encrypted and returned as JWEs."
375        ),
376        related_name="oauth2provider_encryption_key_set",
377    )
378
379    jwt_federation_sources = models.ManyToManyField(
380        OAuthSource,
381        verbose_name=_(
382            "Any JWT signed by the JWK of the selected source can be used to authenticate."
383        ),
384        related_name="oauth2_providers",
385        default=None,
386        blank=True,
387        through="OAuth2ProviderJWTFederationSource",
388    )
389    jwt_federation_providers = models.ManyToManyField(
390        "OAuth2Provider", blank=True, default=None, through="OAuth2ProviderJWTFederationProvider"
391    )
392
393    @cached_property
394    def jwt_key(self) -> tuple[str | PrivateKeyTypes, str]:
395        """Get either the configured certificate or the client secret"""
396        if not self.signing_key:
397            # No Certificate at all, assume HS256
398            return self.client_secret, JWTAlgorithms.HS256
399        key: CertificateKeyPair = self.signing_key
400        private_key = key.private_key
401        return private_key, JWTAlgorithms.from_private_key(private_key)
402
403    @cached_property
404    def jwt_alg(self) -> str:
405        """Get the signing algorithm without loading the private key for signing"""
406        if not self.signing_key:
407            return JWTAlgorithms.HS256
408        return JWTAlgorithms.from_public_key(self.signing_key.public_key)
409
410    def get_issuer(self, request: HttpRequest) -> str | None:
411        """Get issuer, based on request"""
412        if self.issuer_mode == IssuerMode.GLOBAL:
413            return request.build_absolute_uri(reverse("authentik_core:root-redirect"))
414        try:
415            url = reverse(
416                "authentik_providers_oauth2:provider-root",
417                kwargs={
418                    "application_slug": self.application.slug,
419                },
420            )
421            return request.build_absolute_uri(url)
422        except Provider.application.RelatedObjectDoesNotExist:
423            return None
424
425    @property
426    def redirect_uris(self) -> list[RedirectURI]:
427        uris = []
428        for entry in self._redirect_uris:
429            uris.append(
430                from_dict(
431                    RedirectURI,
432                    entry,
433                    config=Config(
434                        type_hooks={
435                            RedirectURIMatchingMode: RedirectURIMatchingMode,
436                            RedirectURIType: RedirectURIType,
437                        }
438                    ),
439                )
440            )
441        return uris
442
443    @redirect_uris.setter
444    def redirect_uris(self, value: list[RedirectURI]):
445        cleansed = []
446        for entry in value:
447            cleansed.append(asdict(entry))
448        self._redirect_uris = cleansed
449
450    @property
451    def authorization_redirect_uris(self) -> list[RedirectURI]:
452        return [
453            uri
454            for uri in self.redirect_uris
455            if uri.redirect_uri_type == RedirectURIType.AUTHORIZATION
456        ]
457
458    @property
459    def post_logout_redirect_uris(self) -> list[RedirectURI]:
460        return [
461            uri for uri in self.redirect_uris if uri.redirect_uri_type == RedirectURIType.LOGOUT
462        ]
463
464    @property
465    def launch_url(self) -> str | None:
466        """Guess launch_url based on first redirect_uri"""
467        redirects = self.authorization_redirect_uris
468        if len(redirects) < 1:
469            return None
470        main_url = redirects[0].url
471        try:
472            launch_url = urlparse(main_url)._replace(path="")
473            return urlunparse(launch_url)
474        except ValueError as exc:
475            LOGGER.warning("Failed to format launch url", exc=exc)
476            return None
477
478    @property
479    def icon_url(self) -> str | None:
480        return static("authentik/sources/openidconnect/light.svg")
481
482    @property
483    def component(self) -> str:
484        return "ak-provider-oauth2-form"
485
486    @property
487    def serializer(self) -> type[Serializer]:
488        from authentik.providers.oauth2.api.providers import OAuth2ProviderSerializer
489
490        return OAuth2ProviderSerializer
491
492    def __str__(self):
493        return f"OAuth2 Provider {self.name}"
494
495    @active_tracer().instrument()
496    def encode(self, payload: dict[str, Any], jwt_type: str | None = None) -> str:
497        """Represent the ID Token as a JSON Web Token (JWT).
498
499        :param payload The payload to encode into the JWT
500        :param jwt_type The type of the JWT. This will be put in the JWT header using the `typ`
501            parameter. See RFC7515 Section 4.1.9. If not set fallback to the default of `JWT`.
502        """
503        headers = {}
504        if self.signing_key:
505            headers["kid"] = self.signing_key.kid
506        if jwt_type is not None:
507            headers["typ"] = jwt_type
508        key, alg = self.jwt_key
509        encoded = encode(payload, key, algorithm=alg, headers=headers)
510        if self.encryption_key:
511            return self.encrypt(encoded)
512        return encoded
513
514    def encrypt(self, raw: str) -> str:
515        """Encrypt JWT"""
516        key = JWK.from_pem(self.encryption_key.certificate_data.encode())
517        jwe = JWE(
518            raw,
519            json_encode(
520                {
521                    "alg": "RSA-OAEP-256",
522                    "enc": "A256CBC-HS512",
523                    "typ": "JWE",
524                    "kid": self.encryption_key.kid,
525                }
526            ),
527        )
528        jwe.add_recipient(key)
529        return jwe.serialize(compact=True)
530
531    def webfinger(self, resource: str, request: HttpRequest):
532        return {
533            "subject": resource,
534            "links": [
535                {
536                    "rel": "http://openid.net/specs/connect/1.0/issuer",
537                    "href": request.build_absolute_uri(
538                        reverse(
539                            "authentik_providers_oauth2:provider-root",
540                            kwargs={
541                                "application_slug": self.application.slug,
542                            },
543                        )
544                    ),
545                },
546            ],
547        }
548
549    class Meta:
550        verbose_name = _("OAuth2/OpenID Provider")
551        verbose_name_plural = _("OAuth2/OpenID Providers")

OAuth2 Provider for generic OAuth and OpenID Connect Applications.

def client_type(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def grant_types(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def client_id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def client_secret(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def logout_uri(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def logout_method(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def include_claims_in_id_token(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def access_code_validity(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def access_token_validity(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def refresh_token_validity(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def refresh_token_threshold(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def refresh_token_revoke_family_on_reuse(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def refresh_token_reuse_grace_period(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def sub_mode(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def issuer_mode(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

signing_key

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

encryption_key

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

jwt_federation_sources

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

jwt_federation_providers

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

jwt_key: tuple[str | cryptography.hazmat.primitives.asymmetric.dh.DHPrivateKey | cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey | cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey | cryptography.hazmat.primitives.asymmetric.mldsa.MLDSA44PrivateKey | cryptography.hazmat.primitives.asymmetric.mldsa.MLDSA65PrivateKey | cryptography.hazmat.primitives.asymmetric.mldsa.MLDSA87PrivateKey | cryptography.hazmat.primitives.asymmetric.mlkem.MLKEM768PrivateKey | cryptography.hazmat.primitives.asymmetric.mlkem.MLKEM1024PrivateKey | cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey | cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey | cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey | cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey | cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey, str]
393    @cached_property
394    def jwt_key(self) -> tuple[str | PrivateKeyTypes, str]:
395        """Get either the configured certificate or the client secret"""
396        if not self.signing_key:
397            # No Certificate at all, assume HS256
398            return self.client_secret, JWTAlgorithms.HS256
399        key: CertificateKeyPair = self.signing_key
400        private_key = key.private_key
401        return private_key, JWTAlgorithms.from_private_key(private_key)

Get either the configured certificate or the client secret

jwt_alg: str
403    @cached_property
404    def jwt_alg(self) -> str:
405        """Get the signing algorithm without loading the private key for signing"""
406        if not self.signing_key:
407            return JWTAlgorithms.HS256
408        return JWTAlgorithms.from_public_key(self.signing_key.public_key)

Get the signing algorithm without loading the private key for signing

def get_issuer(self, request: django.http.request.HttpRequest) -> str | None:
410    def get_issuer(self, request: HttpRequest) -> str | None:
411        """Get issuer, based on request"""
412        if self.issuer_mode == IssuerMode.GLOBAL:
413            return request.build_absolute_uri(reverse("authentik_core:root-redirect"))
414        try:
415            url = reverse(
416                "authentik_providers_oauth2:provider-root",
417                kwargs={
418                    "application_slug": self.application.slug,
419                },
420            )
421            return request.build_absolute_uri(url)
422        except Provider.application.RelatedObjectDoesNotExist:
423            return None

Get issuer, based on request

redirect_uris: list[RedirectURI]
425    @property
426    def redirect_uris(self) -> list[RedirectURI]:
427        uris = []
428        for entry in self._redirect_uris:
429            uris.append(
430                from_dict(
431                    RedirectURI,
432                    entry,
433                    config=Config(
434                        type_hooks={
435                            RedirectURIMatchingMode: RedirectURIMatchingMode,
436                            RedirectURIType: RedirectURIType,
437                        }
438                    ),
439                )
440            )
441        return uris
authorization_redirect_uris: list[RedirectURI]
450    @property
451    def authorization_redirect_uris(self) -> list[RedirectURI]:
452        return [
453            uri
454            for uri in self.redirect_uris
455            if uri.redirect_uri_type == RedirectURIType.AUTHORIZATION
456        ]
post_logout_redirect_uris: list[RedirectURI]
458    @property
459    def post_logout_redirect_uris(self) -> list[RedirectURI]:
460        return [
461            uri for uri in self.redirect_uris if uri.redirect_uri_type == RedirectURIType.LOGOUT
462        ]
launch_url: str | None
464    @property
465    def launch_url(self) -> str | None:
466        """Guess launch_url based on first redirect_uri"""
467        redirects = self.authorization_redirect_uris
468        if len(redirects) < 1:
469            return None
470        main_url = redirects[0].url
471        try:
472            launch_url = urlparse(main_url)._replace(path="")
473            return urlunparse(launch_url)
474        except ValueError as exc:
475            LOGGER.warning("Failed to format launch url", exc=exc)
476            return None

Guess launch_url based on first redirect_uri

icon_url: str | None
478    @property
479    def icon_url(self) -> str | None:
480        return static("authentik/sources/openidconnect/light.svg")
component: str
482    @property
483    def component(self) -> str:
484        return "ak-provider-oauth2-form"

Return component used to edit this object

serializer: type[rest_framework.serializers.Serializer]
486    @property
487    def serializer(self) -> type[Serializer]:
488        from authentik.providers.oauth2.api.providers import OAuth2ProviderSerializer
489
490        return OAuth2ProviderSerializer

Get serializer for this model

@active_tracer().instrument()
def encode(self, payload: dict[str, typing.Any], jwt_type: str | None = None) -> str:
495    @active_tracer().instrument()
496    def encode(self, payload: dict[str, Any], jwt_type: str | None = None) -> str:
497        """Represent the ID Token as a JSON Web Token (JWT).
498
499        :param payload The payload to encode into the JWT
500        :param jwt_type The type of the JWT. This will be put in the JWT header using the `typ`
501            parameter. See RFC7515 Section 4.1.9. If not set fallback to the default of `JWT`.
502        """
503        headers = {}
504        if self.signing_key:
505            headers["kid"] = self.signing_key.kid
506        if jwt_type is not None:
507            headers["typ"] = jwt_type
508        key, alg = self.jwt_key
509        encoded = encode(payload, key, algorithm=alg, headers=headers)
510        if self.encryption_key:
511            return self.encrypt(encoded)
512        return encoded

Represent the ID Token as a JSON Web Token (JWT).

:param payload The payload to encode into the JWT :param jwt_type The type of the JWT. This will be put in the JWT header using the typ parameter. See RFC7515 Section 4.1.9. If not set fallback to the default of JWT.

def encrypt(self, raw: str) -> str:
514    def encrypt(self, raw: str) -> str:
515        """Encrypt JWT"""
516        key = JWK.from_pem(self.encryption_key.certificate_data.encode())
517        jwe = JWE(
518            raw,
519            json_encode(
520                {
521                    "alg": "RSA-OAEP-256",
522                    "enc": "A256CBC-HS512",
523                    "typ": "JWE",
524                    "kid": self.encryption_key.kid,
525                }
526            ),
527        )
528        jwe.add_recipient(key)
529        return jwe.serialize(compact=True)

Encrypt JWT

def webfinger(self, resource: str, request: django.http.request.HttpRequest):
531    def webfinger(self, resource: str, request: HttpRequest):
532        return {
533            "subject": resource,
534            "links": [
535                {
536                    "rel": "http://openid.net/specs/connect/1.0/issuer",
537                    "href": request.build_absolute_uri(
538                        reverse(
539                            "authentik_providers_oauth2:provider-root",
540                            kwargs={
541                                "application_slug": self.application.slug,
542                            },
543                        )
544                    ),
545                },
546            ],
547        }
def get_client_type_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_logout_method_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_sub_mode_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_issuer_mode_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

signing_key_id
encryption_key_id
provider_ptr_id
provider_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

agentconnector_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

agentconnectorjwtfederationprovider_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

oauth2provider_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

oauth2providerjwtfederationsource_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

jwt_federation_provider_m2m_objects

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

oauth2_provider_m2m_objects

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

authorizationcode_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

accesstoken_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

refreshtoken_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

oauth2sessionlogin_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

devicetoken_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

dcr_configuration

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

proxyprovider

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

saml_federation_providers

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

samlproviderjwtfederationprovider_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

ssfprovider_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

ssfprovideroidcauthprovider_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class OAuth2Provider.DoesNotExist(authentik.core.models.Provider.DoesNotExist):

The requested object does not exist

class OAuth2Provider.MultipleObjectsReturned(authentik.core.models.Provider.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class OAuth2ProviderJWTFederationSource(authentik.lib.models.SimpleThroughModel):
554class OAuth2ProviderJWTFederationSource(SimpleThroughModel):
555    oauth2_provider = models.ForeignKey(
556        OAuth2Provider, on_delete=models.CASCADE, db_column="oauth2provider_id"
557    )
558    oauth_source = models.ForeignKey(
559        OAuthSource, on_delete=models.CASCADE, db_column="oauthsource_id"
560    )
561
562    class Meta:
563        db_table = "authentik_providers_oauth2_oauth2provider_jwt_federation_so2b48"
564        unique_together = (("oauth2_provider", "oauth_source"),)
565        verbose_name = _("OAuth2 Provider JWT Federation Source")
566        verbose_name_plural = _("OAuth2 Provider JWT Federation Sources")
567
568    def __str__(self):
569        return (
570            f"OAuth2ProviderJWTFederationSource for OAuth2Provider {self.oauth2_provider_id} "
571            f"and OauthSource {self.oauth_source_id}."
572        )

OAuth2ProviderJWTFederationSource(id, oauth2_provider, oauth_source)

oauth2_provider

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

oauth_source

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

oauth2_provider_id
oauth_source_id
def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def objects(unknown):

The type of the None singleton.

class OAuth2ProviderJWTFederationSource.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class OAuth2ProviderJWTFederationSource.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class OAuth2ProviderJWTFederationProvider(authentik.lib.models.SimpleThroughModel):
575class OAuth2ProviderJWTFederationProvider(SimpleThroughModel):
576    oauth2_provider = models.ForeignKey(
577        OAuth2Provider,
578        on_delete=models.CASCADE,
579        related_name="jwt_federation_provider_m2m_objects",
580        db_column="from_oauth2provider_id",
581    )
582    jwt_federation_provider = models.ForeignKey(
583        OAuth2Provider,
584        on_delete=models.CASCADE,
585        related_name="oauth2_provider_m2m_objects",
586        db_column="to_oauth2provider_id",
587    )
588
589    class Meta:
590        db_table = "authentik_providers_oauth2_oauth2provider_jwt_federation_pr9002"
591        unique_together = (("oauth2_provider", "jwt_federation_provider"),)
592        verbose_name = _("OAuth2 Provider JWT Federation Provider")
593        verbose_name_plural = _("OAuth2 Provider JWT Federation Providers")
594
595    def __str__(self):
596        return (
597            f"OAuth2ProviderJWTFederationProvider for OAuth2Provider {self.oauth2_provider_id} "
598            f"and JWTFederationProvider {self.jwt_federation_provider_id}."
599        )

OAuth2ProviderJWTFederationProvider(id, oauth2_provider, jwt_federation_provider)

oauth2_provider

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

jwt_federation_provider

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

oauth2_provider_id
jwt_federation_provider_id
def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def objects(unknown):

The type of the None singleton.

class OAuth2ProviderJWTFederationProvider.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class OAuth2ProviderJWTFederationProvider.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class BaseGrantModel(django.db.models.base.Model):
602class BaseGrantModel(models.Model):
603    """Base Model for all grants"""
604
605    provider = models.ForeignKey(OAuth2Provider, on_delete=models.CASCADE)
606    user = models.ForeignKey(User, verbose_name=_("User"), on_delete=models.CASCADE)
607    revoked = models.BooleanField(default=False)
608    _scope = models.TextField(default="", verbose_name=_("Scopes"))
609    auth_time = models.DateTimeField(verbose_name="Authentication time")
610    session = models.ForeignKey(
611        AuthenticatedSession, null=True, on_delete=models.CASCADE, default=None
612    )
613    # RFC 8693 §4.1 delegation: set when this grant was obtained via a token-exchange
614    # request presenting an `actor_token` (e.g. an Actor's own API token) alongside the
615    # `subject_token` -- `user` above stays the subject (unchanged), `actor` records who
616    # is actually exercising the token, and is mirrored into the issued token's `act` claim.
617    actor = models.ForeignKey(
618        User,
619        on_delete=models.SET_NULL,
620        related_name="actor_for_%(class)ss",
621        null=True,
622        blank=True,
623        default=None,
624    )
625
626    class Meta:
627        abstract = True
628
629    @property
630    def scope(self) -> list[str]:
631        """Return scopes as list of strings"""
632        return self._scope.split()
633
634    @scope.setter
635    def scope(self, value):
636        self._scope = " ".join(value)

Base Model for all grants

provider

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

user

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def revoked(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def auth_time(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

session

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

actor

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

scope: list[str]
629    @property
630    def scope(self) -> list[str]:
631        """Return scopes as list of strings"""
632        return self._scope.split()

Return scopes as list of strings

provider_id
user_id
def get_next_by_auth_time(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_auth_time(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

session_id
actor_id
class BaseGrantModel.Meta:
626    class Meta:
627        abstract = True
abstract = False
639class AuthorizationCode(InternallyManagedMixin, SerializerModel, ExpiringModel, BaseGrantModel):
640    """OAuth2 Authorization Code"""
641
642    code = models.CharField(max_length=255, unique=True, verbose_name=_("Code"))
643    nonce = models.TextField(null=True, default=None, verbose_name=_("Nonce"))
644    code_challenge = models.CharField(max_length=255, null=True, verbose_name=_("Code Challenge"))
645    code_challenge_method = models.CharField(
646        max_length=255, null=True, verbose_name=_("Code Challenge Method")
647    )
648    dpop_jkt = models.CharField(
649        max_length=255, null=True, default=None, verbose_name=_("DPoP JWK Thumbprint")
650    )
651
652    class Meta:
653        verbose_name = _("Authorization Code")
654        verbose_name_plural = _("Authorization Codes")
655        indexes = ExpiringModel.Meta.indexes
656
657    def __str__(self):
658        return f"Authorization code for {self.provider_id} for user {self.user_id}"
659
660    @property
661    def serializer(self) -> Serializer:
662        from authentik.providers.oauth2.api.tokens import ExpiringBaseGrantModelSerializer
663
664        return ExpiringBaseGrantModelSerializer
665
666    @property
667    def c_hash(self):
668        """https://openid.net/specs/openid-connect-core-1_0.html#IDToken"""
669        hashed_code = sha256(self.code.encode("ascii")).hexdigest().encode("ascii")
670        return (
671            base64.urlsafe_b64encode(binascii.unhexlify(hashed_code[: len(hashed_code) // 2]))
672            .rstrip(b"=")
673            .decode("ascii")
674        )

OAuth2 Authorization Code

def code(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def nonce(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def code_challenge(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def code_challenge_method(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def dpop_jkt(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

serializer: rest_framework.serializers.Serializer
660    @property
661    def serializer(self) -> Serializer:
662        from authentik.providers.oauth2.api.tokens import ExpiringBaseGrantModelSerializer
663
664        return ExpiringBaseGrantModelSerializer

Get serializer for this model

c_hash
666    @property
667    def c_hash(self):
668        """https://openid.net/specs/openid-connect-core-1_0.html#IDToken"""
669        hashed_code = sha256(self.code.encode("ascii")).hexdigest().encode("ascii")
670        return (
671            base64.urlsafe_b64encode(binascii.unhexlify(hashed_code[: len(hashed_code) // 2]))
672            .rstrip(b"=")
673            .decode("ascii")
674        )
def expires(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def expiring(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

provider

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

user

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def revoked(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def auth_time(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

session

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

actor

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

provider_id
user_id
def get_next_by_auth_time(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_auth_time(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

session_id
actor_id
def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

class AuthorizationCode.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class AuthorizationCode.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

677class AccessToken(InternallyManagedMixin, SerializerModel, ExpiringModel, BaseGrantModel):
678    """OAuth2 access token, non-opaque using a JWT as identifier"""
679
680    token = models.TextField()
681    _id_token = models.TextField()
682    # Family of the refresh token issued alongside this token, so the access tokens are revoked
683    # together with the refresh tokens when reuse is detected
684    family = models.UUIDField(null=True, default=None)
685
686    class Meta:
687        indexes = ExpiringModel.Meta.indexes + [
688            HashIndex(fields=["token"]),
689            # Most access tokens have no family (no refresh token was issued), so only index the
690            # ones that do. This keeps the index small and cheap to maintain on insert
691            models.Index(
692                fields=["family"],
693                name="authentik_p_at_family_idx",
694                condition=Q(family__isnull=False),
695            ),
696        ]
697        verbose_name = _("OAuth2 Access Token")
698        verbose_name_plural = _("OAuth2 Access Tokens")
699
700    def __str__(self):
701        return f"Access Token for {self.provider_id} for user {self.user_id}"
702
703    @property
704    def id_token(self) -> IDToken:
705        """Load ID Token from json"""
706        from authentik.providers.oauth2.id_token import IDToken
707
708        raw_token = json.loads(self._id_token)
709        return from_dict(IDToken, raw_token)
710
711    @id_token.setter
712    def id_token(self, value: IDToken):
713        self.token = value.to_access_token(self.provider, self)
714        self._id_token = json.dumps(asdict(value))
715
716    @property
717    def at_hash(self):
718        """Get hashed access_token"""
719        hashed_access_token = sha256(self.token.encode("ascii")).hexdigest().encode("ascii")
720        return (
721            base64.urlsafe_b64encode(
722                binascii.unhexlify(hashed_access_token[: len(hashed_access_token) // 2])
723            )
724            .rstrip(b"=")
725            .decode("ascii")
726        )
727
728    @property
729    def serializer(self) -> Serializer:
730        from authentik.providers.oauth2.api.tokens import TokenModelSerializer
731
732        return TokenModelSerializer

OAuth2 access token, non-opaque using a JWT as identifier

def token(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def family(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

id_token
703    @property
704    def id_token(self) -> IDToken:
705        """Load ID Token from json"""
706        from authentik.providers.oauth2.id_token import IDToken
707
708        raw_token = json.loads(self._id_token)
709        return from_dict(IDToken, raw_token)

Load ID Token from json

at_hash
716    @property
717    def at_hash(self):
718        """Get hashed access_token"""
719        hashed_access_token = sha256(self.token.encode("ascii")).hexdigest().encode("ascii")
720        return (
721            base64.urlsafe_b64encode(
722                binascii.unhexlify(hashed_access_token[: len(hashed_access_token) // 2])
723            )
724            .rstrip(b"=")
725            .decode("ascii")
726        )

Get hashed access_token

serializer: rest_framework.serializers.Serializer
728    @property
729    def serializer(self) -> Serializer:
730        from authentik.providers.oauth2.api.tokens import TokenModelSerializer
731
732        return TokenModelSerializer

Get serializer for this model

def expires(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def expiring(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

provider

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

user

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def revoked(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def auth_time(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

session

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

actor

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

provider_id
user_id
def get_next_by_auth_time(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_auth_time(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

session_id
actor_id
def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

class AccessToken.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class AccessToken.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

735class RefreshToken(InternallyManagedMixin, SerializerModel, ExpiringModel, BaseGrantModel):
736    """OAuth2 Refresh Token, opaque. Tokens are looked up by their hash, see `token`."""
737
738    # Plaintext token column from before refresh tokens were hashed at rest. It is still written,
739    # as the previous authentik version looks tokens up by it: during a rolling upgrade or after
740    # a rollback, that version must be able to find tokens issued by this one, and must never
741    # find a token with no plaintext when it looks up a missing token (`token=None`). A future
742    # release will stop writing it, then remove it. Until then, it is also the lookup fallback
743    # for tokens issued by an older version, which have no hash.
744    legacy_token = models.TextField(db_column="token", null=True, default=None)
745    # Tokens issued by an older version have no hash until they are next saved
746    token_hash = models.TextField(null=True, default=None)
747    # All refresh tokens rotated from the same authorization share a family, so that reuse of a
748    # rotated token can revoke the whole chain (RFC 9700 Section 4.14.2). Tokens issued by an
749    # older version have no family until they are refreshed.
750    family = models.UUIDField(null=True, default=uuid4)
751    rotated_at = models.DateTimeField(null=True, default=None)
752    _id_token = models.TextField(verbose_name=_("ID Token"))
753    dpop_jkt = models.CharField(
754        max_length=255, null=True, default=None, verbose_name=_("DPoP JWK Thumbprint")
755    )
756    # Shadow the `session` field from `BaseGrantModel` as we want refresh tokens to persist even
757    # when the session is terminated.
758    session = models.ForeignKey(
759        AuthenticatedSession, null=True, on_delete=models.SET_DEFAULT, default=None
760    )
761
762    _raw_token: str | None = None
763
764    class Meta:
765        indexes = ExpiringModel.Meta.indexes + [
766            HashIndex(fields=["legacy_token"]),
767            HashIndex(fields=["token_hash"]),
768            # Tokens issued by an older version have no family, only index the ones that do
769            models.Index(
770                fields=["family"],
771                name="authentik_p_rt_family_idx",
772                condition=Q(family__isnull=False),
773            ),
774        ]
775        verbose_name = _("OAuth2 Refresh Token")
776        verbose_name_plural = _("OAuth2 Refresh Tokens")
777
778    def __str__(self):
779        return f"Refresh Token for {self.provider_id} for user {self.user_id}"
780
781    def save(self, *args, **kwargs):
782        if not self.token_hash:
783            if self.legacy_token:
784                # Issued by an older version, hash it so lookups don't need the fallback
785                self.token_hash = hash_refresh_token(self.legacy_token)
786            else:
787                self.token = generate_client_secret()
788        return super().save(*args, **kwargs)
789
790    @property
791    def token(self) -> str | None:
792        """The raw token value. Only set on a token created in this process (to return it to
793        the client), never on one loaded from the database, which is looked up by its hash."""
794        return self._raw_token
795
796    @token.setter
797    def token(self, value: str | None):
798        self._raw_token = value
799        self.token_hash = hash_refresh_token(value) if value else None
800        # Still written for the previous version, see `legacy_token`
801        self.legacy_token = value
802
803    @staticmethod
804    def token_query(raw: str | None) -> Q:
805        """Query matching the refresh token with the raw value `raw`"""
806        if not raw:
807            # Never fall through to `legacy_token=None`, which matches every hashed token
808            return Q(pk__in=[])
809        return Q(token_hash=hash_refresh_token(raw)) | Q(legacy_token=raw)
810
811    @staticmethod
812    def lock_family(family: UUID) -> None:
813        """Lock the family `family` until the current transaction ends. Refreshing a token
814        (which may issue tokens of its family), revoking a family on reuse and revoking it via
815        RFC 7009 hold this lock while doing so.
816
817        Revoking a family is an UPDATE of its tokens, and an UPDATE can't see a token inserted
818        by a concurrent transaction which hasn't committed yet. Without the lock, a token issued
819        concurrently (by a rotation, or within the reuse grace period) would escape the
820        revocation. With it, the revocation waits until that token is committed, or the request
821        issuing it waits until the revocation is committed and then sees it.
822
823        Deleting tokens by user, session or expiry doesn't take the lock. A refresh racing with
824        such a deletion either fails because its token is gone, or issues tokens which the
825        deletion doesn't see."""
826        if not family:
827            # Every token without a family would share this lock
828            raise ValueError("Tokens without a family can't be locked")
829        if not connection.in_atomic_block:
830            # Outside of a transaction the lock would be released immediately
831            raise TransactionManagementError(
832                "Refresh token families can only be locked in a transaction"
833            )
834        with connection.cursor() as cursor:
835            cursor.execute(
836                "SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))",
837                [f"authentik_providers_oauth2.refreshtoken.family:{family}"],
838            )
839
840    def start_family(self) -> None:
841        """Start a family for a token issued before refresh token families existed, and hash it.
842        Concurrent requests presenting the same token may race here, so only the first one sets
843        the family, and all of them use that one. Raises `DoesNotExist` when the token has been
844        deleted.
845
846        Includes expired tokens, so that a token which expired since it was loaded still gets
847        its family: `refresh_from_db` would load it anyway, and a caller filtering by its unset
848        family would match every token without a family."""
849        if self.family:
850            return
851        update: dict[str, Any] = {"family": uuid4()}
852        if not self.token_hash and self.legacy_token:
853            update["token_hash"] = hash_refresh_token(self.legacy_token)
854        RefreshToken.objects.including_expired().filter(pk=self.pk, family__isnull=True).update(
855            **update
856        )
857        self.refresh_from_db(fields=["family", "token_hash"])
858
859    def consume(self, now: datetime) -> bool:
860        """Rotate this token: mark it as revoked, keeping it so its reuse can be detected.
861
862        Called with the family locked (see `lock_family`). It is still a single conditional
863        update, so that it fails rather than issuing a second successor when the token was
864        changed by something which doesn't hold the lock (such as the previous version during a
865        rolling upgrade). Then it returns False, and the request must be treated as reuse."""
866        consumed = (
867            RefreshToken.objects.including_expired()
868            .filter(pk=self.pk, revoked=False)
869            .update(revoked=True, rotated_at=now)
870            == 1
871        )
872        if consumed:
873            self.revoked = True
874            self.rotated_at = now
875        return consumed
876
877    def claim_reuse_grace(self, rotated_after: datetime) -> bool:
878        """Check whether this rotated token may be used again within the reuse grace period,
879        because it is the most recently rotated token of a family which still has an active
880        token, and it was rotated after `rotated_after`.
881
882        Called with the family locked (see `lock_family`), so that the token issued within the
883        grace period can't escape a concurrent revocation of the family. The rotation time is
884        kept, so that repeated reuse can't extend the grace period."""
885        if not self.family:
886            # Never compare with `family=None`, which would match every token without a family
887            return False
888        family = RefreshToken.objects.filter(family=OuterRef("family"))
889        return (
890            RefreshToken.objects.including_expired()
891            .filter(
892                pk=self.pk,
893                revoked=True,
894                rotated_at__gt=rotated_after,
895            )
896            .filter(
897                # Another token was rotated since, so this one isn't the most recently rotated
898                ~Exists(family.filter(rotated_at__gt=OuterRef("rotated_at"))),
899                # The family has been revoked (or its active token revoked via RFC 7009)
900                Exists(family.filter(revoked=False)),
901            )
902            .update(rotated_at=F("rotated_at"))
903            == 1
904        )
905
906    def revoke_family(self) -> None:
907        """Revoke all refresh and access tokens of this token's family, when reuse of a rotated
908        token is detected. The refresh tokens are kept, so that their reuse is still detected."""
909        self.revoked = True
910        with transaction.atomic():
911            if not self.family:
912                # Never filter by `family=None`, which would match every token without a family
913                RefreshToken.objects.filter(pk=self.pk).update(revoked=True)
914                return
915            self.lock_family(self.family)
916            RefreshToken.objects.including_expired().filter(
917                family=self.family, revoked=False
918            ).update(revoked=True)
919            # Deleted rather than marked as revoked: not everything which accepts access tokens
920            # checks `revoked` (API authentication, DCR, the endpoint agent, JWT federation)
921            AccessToken.objects.including_expired().filter(family=self.family).delete()
922
923    def delete_family(self) -> None:
924        """Delete all refresh and access tokens of this token's family, when it is revoked by
925        the client (RFC 7009 Section 2.1). This includes the other tokens issued for retries
926        within the reuse grace period, which the client may not know about."""
927        with transaction.atomic():
928            if not self.family:
929                # Issued before refresh token families existed. Start its family like a refresh
930                # does, so that a concurrent refresh of this token (which may already have
931                # started it, and be issuing tokens of it) is serialized with this through the
932                # family's lock
933                try:
934                    self.start_family()
935                except RefreshToken.DoesNotExist:
936                    return
937            if not self.family:
938                # Never filter by `family=None`, which would match every token without a family
939                return
940            self.lock_family(self.family)
941            AccessToken.objects.including_expired().filter(family=self.family).delete()
942            RefreshToken.objects.including_expired().filter(family=self.family).delete()
943
944    @property
945    def id_token(self) -> IDToken:
946        """Load ID Token from json"""
947        from authentik.providers.oauth2.id_token import IDToken
948
949        raw_token = json.loads(self._id_token)
950        return from_dict(IDToken, raw_token)
951
952    @id_token.setter
953    def id_token(self, value: IDToken):
954        self._id_token = json.dumps(asdict(value))
955
956    @property
957    def serializer(self) -> Serializer:
958        from authentik.providers.oauth2.api.tokens import TokenModelSerializer
959
960        return TokenModelSerializer

OAuth2 Refresh Token, opaque. Tokens are looked up by their hash, see token.

def legacy_token(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def token_hash(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def family(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def rotated_at(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def dpop_jkt(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

session

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def save(self, *args, **kwargs):
781    def save(self, *args, **kwargs):
782        if not self.token_hash:
783            if self.legacy_token:
784                # Issued by an older version, hash it so lookups don't need the fallback
785                self.token_hash = hash_refresh_token(self.legacy_token)
786            else:
787                self.token = generate_client_secret()
788        return super().save(*args, **kwargs)

Save the current instance. Override this in a subclass if you want to control the saving process.

The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

token: str | None
790    @property
791    def token(self) -> str | None:
792        """The raw token value. Only set on a token created in this process (to return it to
793        the client), never on one loaded from the database, which is looked up by its hash."""
794        return self._raw_token

The raw token value. Only set on a token created in this process (to return it to the client), never on one loaded from the database, which is looked up by its hash.

@staticmethod
def token_query(raw: str | None) -> django.db.models.query_utils.Q:
803    @staticmethod
804    def token_query(raw: str | None) -> Q:
805        """Query matching the refresh token with the raw value `raw`"""
806        if not raw:
807            # Never fall through to `legacy_token=None`, which matches every hashed token
808            return Q(pk__in=[])
809        return Q(token_hash=hash_refresh_token(raw)) | Q(legacy_token=raw)

Query matching the refresh token with the raw value raw

@staticmethod
def lock_family(family: uuid.UUID) -> None:
811    @staticmethod
812    def lock_family(family: UUID) -> None:
813        """Lock the family `family` until the current transaction ends. Refreshing a token
814        (which may issue tokens of its family), revoking a family on reuse and revoking it via
815        RFC 7009 hold this lock while doing so.
816
817        Revoking a family is an UPDATE of its tokens, and an UPDATE can't see a token inserted
818        by a concurrent transaction which hasn't committed yet. Without the lock, a token issued
819        concurrently (by a rotation, or within the reuse grace period) would escape the
820        revocation. With it, the revocation waits until that token is committed, or the request
821        issuing it waits until the revocation is committed and then sees it.
822
823        Deleting tokens by user, session or expiry doesn't take the lock. A refresh racing with
824        such a deletion either fails because its token is gone, or issues tokens which the
825        deletion doesn't see."""
826        if not family:
827            # Every token without a family would share this lock
828            raise ValueError("Tokens without a family can't be locked")
829        if not connection.in_atomic_block:
830            # Outside of a transaction the lock would be released immediately
831            raise TransactionManagementError(
832                "Refresh token families can only be locked in a transaction"
833            )
834        with connection.cursor() as cursor:
835            cursor.execute(
836                "SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))",
837                [f"authentik_providers_oauth2.refreshtoken.family:{family}"],
838            )

Lock the family family until the current transaction ends. Refreshing a token (which may issue tokens of its family), revoking a family on reuse and revoking it via RFC 7009 hold this lock while doing so.

Revoking a family is an UPDATE of its tokens, and an UPDATE can't see a token inserted by a concurrent transaction which hasn't committed yet. Without the lock, a token issued concurrently (by a rotation, or within the reuse grace period) would escape the revocation. With it, the revocation waits until that token is committed, or the request issuing it waits until the revocation is committed and then sees it.

Deleting tokens by user, session or expiry doesn't take the lock. A refresh racing with such a deletion either fails because its token is gone, or issues tokens which the deletion doesn't see.

def start_family(self) -> None:
840    def start_family(self) -> None:
841        """Start a family for a token issued before refresh token families existed, and hash it.
842        Concurrent requests presenting the same token may race here, so only the first one sets
843        the family, and all of them use that one. Raises `DoesNotExist` when the token has been
844        deleted.
845
846        Includes expired tokens, so that a token which expired since it was loaded still gets
847        its family: `refresh_from_db` would load it anyway, and a caller filtering by its unset
848        family would match every token without a family."""
849        if self.family:
850            return
851        update: dict[str, Any] = {"family": uuid4()}
852        if not self.token_hash and self.legacy_token:
853            update["token_hash"] = hash_refresh_token(self.legacy_token)
854        RefreshToken.objects.including_expired().filter(pk=self.pk, family__isnull=True).update(
855            **update
856        )
857        self.refresh_from_db(fields=["family", "token_hash"])

Start a family for a token issued before refresh token families existed, and hash it. Concurrent requests presenting the same token may race here, so only the first one sets the family, and all of them use that one. Raises DoesNotExist when the token has been deleted.

Includes expired tokens, so that a token which expired since it was loaded still gets its family: refresh_from_db would load it anyway, and a caller filtering by its unset family would match every token without a family.

def consume(self, now: datetime.datetime) -> bool:
859    def consume(self, now: datetime) -> bool:
860        """Rotate this token: mark it as revoked, keeping it so its reuse can be detected.
861
862        Called with the family locked (see `lock_family`). It is still a single conditional
863        update, so that it fails rather than issuing a second successor when the token was
864        changed by something which doesn't hold the lock (such as the previous version during a
865        rolling upgrade). Then it returns False, and the request must be treated as reuse."""
866        consumed = (
867            RefreshToken.objects.including_expired()
868            .filter(pk=self.pk, revoked=False)
869            .update(revoked=True, rotated_at=now)
870            == 1
871        )
872        if consumed:
873            self.revoked = True
874            self.rotated_at = now
875        return consumed

Rotate this token: mark it as revoked, keeping it so its reuse can be detected.

Called with the family locked (see lock_family). It is still a single conditional update, so that it fails rather than issuing a second successor when the token was changed by something which doesn't hold the lock (such as the previous version during a rolling upgrade). Then it returns False, and the request must be treated as reuse.

def claim_reuse_grace(self, rotated_after: datetime.datetime) -> bool:
877    def claim_reuse_grace(self, rotated_after: datetime) -> bool:
878        """Check whether this rotated token may be used again within the reuse grace period,
879        because it is the most recently rotated token of a family which still has an active
880        token, and it was rotated after `rotated_after`.
881
882        Called with the family locked (see `lock_family`), so that the token issued within the
883        grace period can't escape a concurrent revocation of the family. The rotation time is
884        kept, so that repeated reuse can't extend the grace period."""
885        if not self.family:
886            # Never compare with `family=None`, which would match every token without a family
887            return False
888        family = RefreshToken.objects.filter(family=OuterRef("family"))
889        return (
890            RefreshToken.objects.including_expired()
891            .filter(
892                pk=self.pk,
893                revoked=True,
894                rotated_at__gt=rotated_after,
895            )
896            .filter(
897                # Another token was rotated since, so this one isn't the most recently rotated
898                ~Exists(family.filter(rotated_at__gt=OuterRef("rotated_at"))),
899                # The family has been revoked (or its active token revoked via RFC 7009)
900                Exists(family.filter(revoked=False)),
901            )
902            .update(rotated_at=F("rotated_at"))
903            == 1
904        )

Check whether this rotated token may be used again within the reuse grace period, because it is the most recently rotated token of a family which still has an active token, and it was rotated after rotated_after.

Called with the family locked (see lock_family), so that the token issued within the grace period can't escape a concurrent revocation of the family. The rotation time is kept, so that repeated reuse can't extend the grace period.

def revoke_family(self) -> None:
906    def revoke_family(self) -> None:
907        """Revoke all refresh and access tokens of this token's family, when reuse of a rotated
908        token is detected. The refresh tokens are kept, so that their reuse is still detected."""
909        self.revoked = True
910        with transaction.atomic():
911            if not self.family:
912                # Never filter by `family=None`, which would match every token without a family
913                RefreshToken.objects.filter(pk=self.pk).update(revoked=True)
914                return
915            self.lock_family(self.family)
916            RefreshToken.objects.including_expired().filter(
917                family=self.family, revoked=False
918            ).update(revoked=True)
919            # Deleted rather than marked as revoked: not everything which accepts access tokens
920            # checks `revoked` (API authentication, DCR, the endpoint agent, JWT federation)
921            AccessToken.objects.including_expired().filter(family=self.family).delete()

Revoke all refresh and access tokens of this token's family, when reuse of a rotated token is detected. The refresh tokens are kept, so that their reuse is still detected.

def delete_family(self) -> None:
923    def delete_family(self) -> None:
924        """Delete all refresh and access tokens of this token's family, when it is revoked by
925        the client (RFC 7009 Section 2.1). This includes the other tokens issued for retries
926        within the reuse grace period, which the client may not know about."""
927        with transaction.atomic():
928            if not self.family:
929                # Issued before refresh token families existed. Start its family like a refresh
930                # does, so that a concurrent refresh of this token (which may already have
931                # started it, and be issuing tokens of it) is serialized with this through the
932                # family's lock
933                try:
934                    self.start_family()
935                except RefreshToken.DoesNotExist:
936                    return
937            if not self.family:
938                # Never filter by `family=None`, which would match every token without a family
939                return
940            self.lock_family(self.family)
941            AccessToken.objects.including_expired().filter(family=self.family).delete()
942            RefreshToken.objects.including_expired().filter(family=self.family).delete()

Delete all refresh and access tokens of this token's family, when it is revoked by the client (RFC 7009 Section 2.1). This includes the other tokens issued for retries within the reuse grace period, which the client may not know about.

id_token
944    @property
945    def id_token(self) -> IDToken:
946        """Load ID Token from json"""
947        from authentik.providers.oauth2.id_token import IDToken
948
949        raw_token = json.loads(self._id_token)
950        return from_dict(IDToken, raw_token)

Load ID Token from json

serializer: rest_framework.serializers.Serializer
956    @property
957    def serializer(self) -> Serializer:
958        from authentik.providers.oauth2.api.tokens import TokenModelSerializer
959
960        return TokenModelSerializer

Get serializer for this model

def expires(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def expiring(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

provider

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

user

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def revoked(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def auth_time(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

actor

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

session_id
provider_id
user_id
def get_next_by_auth_time(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_auth_time(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

actor_id
def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

class RefreshToken.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class RefreshToken.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class OAuth2SessionLogin(authentik.lib.models.InternallyManagedMixin, django.db.models.base.Model):
963class OAuth2SessionLogin(InternallyManagedMixin, models.Model):
964    """Record of providers the user has logged in to this session. required for
965    front/backchannel logout because tokens can expire before the RP's session ends.
966
967    https://openid.net/specs/openid-connect-frontchannel-1_0.html#OPLogout
968    https://openid.net/specs/openid-connect-backchannel-1_0.html#Tracking"""
969
970    session = models.ForeignKey(AuthenticatedSession, on_delete=models.CASCADE)
971    provider = models.ForeignKey(OAuth2Provider, on_delete=models.CASCADE)
972    # Stored as issued to the RP, as the issuer can't be resolved without a request and the
973    # provider's `sub_mode` might change during the lifetime of the session.
974    iss = models.TextField()
975    sub = models.TextField()
976
977    class Meta:
978        verbose_name = _("OAuth2 Session Login")
979        verbose_name_plural = _("OAuth2 Session Logins")
980        constraints = [
981            models.UniqueConstraint(
982                fields=("session", "provider"), name="oauth2_session_login_unique"
983            ),
984        ]
985
986    def __str__(self):
987        return f"Session Login for {self.provider_id} for session {self.session_id}"
988
989    @classmethod
990    def record(cls, token: BaseGrantModel, id_token: IDToken) -> None:
991        """Remember that the provider of `token` has been issued `id_token` for its session"""
992        if not token.session_id:
993            return
994        cls.objects.update_or_create(
995            session_id=token.session_id,
996            provider=token.provider,
997            defaults={"iss": id_token.iss, "sub": id_token.sub},
998        )

Record of providers the user has logged in to this session. required for front/backchannel logout because tokens can expire before the RP's session ends.

https://openid.net/specs/openid-connect-frontchannel-1_0.html#OPLogout https://openid.net/specs/openid-connect-backchannel-1_0.html#Tracking

session

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

provider

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def iss(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def sub(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

@classmethod
def record(unknown):
989    @classmethod
990    def record(cls, token: BaseGrantModel, id_token: IDToken) -> None:
991        """Remember that the provider of `token` has been issued `id_token` for its session"""
992        if not token.session_id:
993            return
994        cls.objects.update_or_create(
995            session_id=token.session_id,
996            provider=token.provider,
997            defaults={"iss": id_token.iss, "sub": id_token.sub},
998        )

Remember that the provider of token has been issued id_token for its session

session_id
provider_id
def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def objects(unknown):

The type of the None singleton.

class OAuth2SessionLogin.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class OAuth2SessionLogin.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

1001class DeviceToken(InternallyManagedMixin, ExpiringModel):
1002    """Temporary device token for OAuth device flow"""
1003
1004    user = models.ForeignKey(
1005        "authentik_core.User", default=None, on_delete=models.CASCADE, null=True
1006    )
1007    provider = models.ForeignKey(OAuth2Provider, on_delete=models.CASCADE)
1008    device_code = models.TextField(default=generate_key)
1009    user_code = models.TextField(default=generate_code_fixed_length)
1010    _scope = models.TextField(default="", verbose_name=_("Scopes"))
1011    dpop_jkt = models.CharField(
1012        max_length=255, null=True, default=None, verbose_name=_("DPoP JWK Thumbprint")
1013    )
1014    session = models.ForeignKey(
1015        AuthenticatedSession, null=True, on_delete=models.SET_DEFAULT, default=None
1016    )
1017
1018    @property
1019    def scope(self) -> list[str]:
1020        """Return scopes as list of strings"""
1021        return self._scope.split()
1022
1023    @scope.setter
1024    def scope(self, value):
1025        self._scope = " ".join(value)
1026
1027    class Meta:
1028        verbose_name = _("Device Token")
1029        verbose_name_plural = _("Device Tokens")
1030        indexes = ExpiringModel.Meta.indexes
1031
1032    def __str__(self):
1033        return f"Device Token for {self.provider_id}"

Temporary device token for OAuth device flow

user

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

provider

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def device_code(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def user_code(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def dpop_jkt(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

session

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

scope: list[str]
1018    @property
1019    def scope(self) -> list[str]:
1020        """Return scopes as list of strings"""
1021        return self._scope.split()

Return scopes as list of strings

def expires(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def expiring(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

user_id
provider_id
session_id
def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

class DeviceToken.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class DeviceToken.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class OAuth2DynamicClientRegistration(authentik.lib.models.SerializerModel, authentik.policies.models.PolicyBindingModel):
1036class OAuth2DynamicClientRegistration(SerializerModel, PolicyBindingModel):
1037    """Configuration for Dynamic Client Registration (RFC 7591) on an OAuth2Provider."""
1038
1039    provider = models.OneToOneField(
1040        OAuth2Provider,
1041        on_delete=models.CASCADE,
1042        related_name="dcr_configuration",
1043        verbose_name=_("Provider"),
1044    )
1045
1046    default_application_group = models.TextField(
1047        blank=True,
1048        default="",
1049        verbose_name=_("Default application group"),
1050        help_text=_("Group to assign to automatically created applications."),
1051    )
1052
1053    override_authorization_flow = models.ForeignKey(
1054        "authentik_flows.Flow",
1055        on_delete=models.SET_NULL,
1056        null=True,
1057        blank=True,
1058        verbose_name=_("Override authorization flow"),
1059        help_text=_("Authorization flow applied to dynamically registered clients."),
1060        related_name="dcr_override_authorization_flow",
1061    )
1062    override_invalidation_flow = models.ForeignKey(
1063        "authentik_flows.Flow",
1064        on_delete=models.SET_NULL,
1065        null=True,
1066        blank=True,
1067        verbose_name=_("Override invalidation flow"),
1068        related_name="dcr_override_invalidation_flow",
1069    )
1070    override_property_mappings = models.ManyToManyField(
1071        ScopeMapping,
1072        blank=True,
1073        verbose_name=_("Override property mappings"),
1074        help_text=_("Scope mappings applied to dynamically registered clients."),
1075        through="DynamicClientRegistrationPropertyMapping",
1076    )
1077
1078    access_token_validity = models.TextField(
1079        default="hours=1",
1080        validators=[timedelta_string_validator],
1081        verbose_name=_("Access token validity"),
1082        help_text=_(
1083            "Maximum access token validity for registered clients "
1084            "(Format: hours=1;minutes=2;seconds=3)."
1085        ),
1086    )
1087    refresh_token_validity = models.TextField(
1088        default="days=30",
1089        validators=[timedelta_string_validator],
1090        verbose_name=_("Refresh token validity"),
1091        help_text=_(
1092            "Maximum refresh token validity for registered clients "
1093            "(Format: hours=1;minutes=2;seconds=3)."
1094        ),
1095    )
1096
1097    allowed_grant_types = ArrayField(
1098        models.TextField(choices=GrantType.choices),
1099        default=list,
1100        blank=True,
1101        verbose_name=_("Allowed grant types"),
1102        help_text=_("If empty, all grant types are allowed."),
1103    )
1104
1105    @property
1106    def serializer(self) -> type[Serializer]:
1107        from authentik.providers.oauth2.api.dcr import (
1108            OAuth2DynamicClientRegistrationSerializer,
1109        )
1110
1111        return OAuth2DynamicClientRegistrationSerializer
1112
1113    def __str__(self):
1114        return f"DCR Configuration for {self.provider_id}"
1115
1116    class Meta:
1117        verbose_name = _("OAuth2 Dynamic Client Registration")
1118        verbose_name_plural = _("OAuth2 Dynamic Client Registrations")

Configuration for Dynamic Client Registration (RFC 7591) on an OAuth2Provider.

provider

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

def default_application_group(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

override_authorization_flow

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

override_invalidation_flow

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

override_property_mappings

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

def access_token_validity(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def refresh_token_validity(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def allowed_grant_types(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

serializer: type[rest_framework.serializers.Serializer]
1105    @property
1106    def serializer(self) -> type[Serializer]:
1107        from authentik.providers.oauth2.api.dcr import (
1108            OAuth2DynamicClientRegistrationSerializer,
1109        )
1110
1111        return OAuth2DynamicClientRegistrationSerializer

Get serializer for this model

provider_id
override_authorization_flow_id
override_invalidation_flow_id
policybindingmodel_ptr_id
policybindingmodel_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

dynamicclientregistrationpropertymapping_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class OAuth2DynamicClientRegistration.DoesNotExist(authentik.policies.models.PolicyBindingModel.DoesNotExist):

The requested object does not exist

class OAuth2DynamicClientRegistration.MultipleObjectsReturned(authentik.policies.models.PolicyBindingModel.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class DynamicClientRegistrationPropertyMapping(authentik.lib.models.SimpleThroughModel):
1121class DynamicClientRegistrationPropertyMapping(SimpleThroughModel):
1122    property_mapping = models.ForeignKey(ScopeMapping, on_delete=models.CASCADE)
1123    dynamic_client_registration = models.ForeignKey(
1124        OAuth2DynamicClientRegistration, on_delete=models.CASCADE
1125    )
1126
1127    class Meta:
1128        unique_together = (("property_mapping", "dynamic_client_registration"),)
1129        verbose_name = _("Dynamic Client Registration Property Mapping")
1130        verbose_name_plural = _("Dynamic Client Registration Property Mappings")
1131
1132    def __str__(self):
1133        return (
1134            "DynamicClientRegistrationPropertyMapping for DCR "
1135            f"{self.dynamic_client_registration_id} and PropertyMapping "
1136            f"{self.property_mapping_id}."
1137        )

DynamicClientRegistrationPropertyMapping(id, property_mapping, dynamic_client_registration)

property_mapping

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

dynamic_client_registration

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

property_mapping_id
dynamic_client_registration_id
def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def objects(unknown):

The type of the None singleton.

class DynamicClientRegistrationPropertyMapping.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class DynamicClientRegistrationPropertyMapping.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.