authentik.sources.saml.models

saml sp models

  1"""saml sp models"""
  2
  3from typing import Any
  4
  5from django.db import models
  6from django.http import HttpRequest
  7from django.templatetags.static import static
  8from django.urls import reverse
  9from django.utils.translation import gettext_lazy as _
 10from lxml.etree import _Element  # nosec
 11from rest_framework.serializers import Serializer
 12
 13from authentik.common.saml.constants import (
 14    DSA_SHA1,
 15    ECDSA_SHA1,
 16    ECDSA_SHA256,
 17    ECDSA_SHA384,
 18    ECDSA_SHA512,
 19    NS_SAML_ASSERTION,
 20    RSA_SHA1,
 21    RSA_SHA256,
 22    RSA_SHA384,
 23    RSA_SHA512,
 24    SAML_ATTRIBUTES_GROUP,
 25    SAML_BINDING_POST,
 26    SAML_BINDING_REDIRECT,
 27    SAML_NAME_ID_FORMAT_EMAIL,
 28    SAML_NAME_ID_FORMAT_PERSISTENT,
 29    SAML_NAME_ID_FORMAT_TRANSIENT,
 30    SAML_NAME_ID_FORMAT_UNSPECIFIED,
 31    SAML_NAME_ID_FORMAT_WINDOWS,
 32    SAML_NAME_ID_FORMAT_X509,
 33    SHA1,
 34    SHA256,
 35    SHA384,
 36    SHA512,
 37)
 38from authentik.common.saml.utils import get_element_text
 39from authentik.core.models import (
 40    GroupSourceConnection,
 41    PropertyMapping,
 42    Source,
 43    UserSourceConnection,
 44)
 45from authentik.core.types import UILoginButton, UserSettingSerializer
 46from authentik.crypto.models import CertificateKeyPair
 47from authentik.flows.challenge import RedirectChallenge
 48from authentik.flows.models import Flow
 49from authentik.lib.expression.evaluator import BaseEvaluator
 50from authentik.lib.models import DomainlessURLValidator
 51from authentik.lib.utils.time import timedelta_string_validator
 52
 53
 54class SAMLBindingTypes(models.TextChoices):
 55    """SAML Binding types"""
 56
 57    REDIRECT = "REDIRECT", _("Redirect Binding")
 58    POST = "POST", _("POST Binding")
 59    POST_AUTO = "POST_AUTO", _("POST Binding with auto-confirmation")
 60
 61    @property
 62    def uri(self) -> str:
 63        """Convert database field to URI"""
 64        return {
 65            SAMLBindingTypes.POST: SAML_BINDING_POST,
 66            SAMLBindingTypes.POST_AUTO: SAML_BINDING_POST,
 67            SAMLBindingTypes.REDIRECT: SAML_BINDING_REDIRECT,
 68        }[self]
 69
 70
 71class SAMLNameIDPolicy(models.TextChoices):
 72    """SAML NameID Policies"""
 73
 74    EMAIL = SAML_NAME_ID_FORMAT_EMAIL
 75    PERSISTENT = SAML_NAME_ID_FORMAT_PERSISTENT
 76    X509 = SAML_NAME_ID_FORMAT_X509
 77    WINDOWS = SAML_NAME_ID_FORMAT_WINDOWS
 78    TRANSIENT = SAML_NAME_ID_FORMAT_TRANSIENT
 79    UNSPECIFIED = SAML_NAME_ID_FORMAT_UNSPECIFIED
 80
 81
 82class SAMLSource(Source):
 83    """Authenticate using an external SAML Identity Provider."""
 84
 85    pre_authentication_flow = models.ForeignKey(
 86        Flow,
 87        on_delete=models.CASCADE,
 88        help_text=_("Flow used before authentication."),
 89        related_name="source_pre_authentication",
 90    )
 91
 92    issuer_override = models.TextField(
 93        blank=True,
 94        default="",
 95        help_text=_("Also known as Entity ID. Defaults to the Metadata URL."),
 96    )
 97
 98    sso_url = models.TextField(
 99        validators=[DomainlessURLValidator(schemes=("http", "https"))],
100        verbose_name=_("SSO URL"),
101        help_text=_("URL that the initial Login request is sent to."),
102    )
103    slo_url = models.TextField(
104        validators=[DomainlessURLValidator(schemes=("http", "https"))],
105        default=None,
106        blank=True,
107        null=True,
108        verbose_name=_("SLO URL"),
109        help_text=_("Optional URL if your IDP supports Single-Logout."),
110    )
111
112    allow_idp_initiated = models.BooleanField(
113        default=False,
114        help_text=_(
115            "Allows authentication flows initiated by the IdP. This can be a security risk, "
116            "as no validation of the request ID is done."
117        ),
118    )
119    force_authn = models.BooleanField(
120        default=False,
121        help_text=_(
122            "When enabled, the IdP will re-authenticate the user even if a session exists."
123        ),
124    )
125    name_id_policy = models.TextField(
126        choices=SAMLNameIDPolicy.choices,
127        default=SAMLNameIDPolicy.PERSISTENT,
128        help_text=_(
129            "Format of the NameID Policy sent to the IdP. Select Unspecified to let the IdP "
130            "choose the format of the NameID it returns."
131        ),
132    )
133    binding_type = models.CharField(
134        max_length=100,
135        choices=SAMLBindingTypes.choices,
136        default=SAMLBindingTypes.REDIRECT,
137    )
138
139    temporary_user_delete_after = models.TextField(
140        default="days=1",
141        verbose_name=_("Delete temporary users after"),
142        validators=[timedelta_string_validator],
143        help_text=_(
144            "Time offset when temporary users should be deleted. This only applies if your IDP "
145            "uses the NameID Format 'transient', and the user doesn't log out manually. "
146            "(Format: hours=1;minutes=2;seconds=3)."
147        ),
148    )
149
150    verification_kp = models.ForeignKey(
151        CertificateKeyPair,
152        default=None,
153        null=True,
154        blank=True,
155        help_text=_(
156            "When selected, incoming assertion's Signatures will be validated against this "
157            "certificate. To allow unsigned Requests, leave on default."
158        ),
159        on_delete=models.SET_NULL,
160        verbose_name=_("Verification Certificate"),
161        related_name="+",
162    )
163    signing_kp = models.ForeignKey(
164        CertificateKeyPair,
165        default=None,
166        null=True,
167        blank=True,
168        help_text=_("Keypair used to sign outgoing Responses going to the Identity Provider."),
169        on_delete=models.SET_NULL,
170        verbose_name=_("Signing Keypair"),
171    )
172    encryption_kp = models.ForeignKey(
173        CertificateKeyPair,
174        default=None,
175        null=True,
176        blank=True,
177        help_text=_(
178            "When selected, incoming assertions are encrypted by the IdP using the public "
179            "key of the encryption keypair. The assertion is decrypted by the SP using the "
180            "the private key."
181        ),
182        on_delete=models.SET_NULL,
183        verbose_name=_("Encryption Keypair"),
184        related_name="+",
185    )
186
187    digest_algorithm = models.TextField(
188        choices=(
189            (SHA1, _("SHA1")),
190            (SHA256, _("SHA256")),
191            (SHA384, _("SHA384")),
192            (SHA512, _("SHA512")),
193        ),
194        default=SHA256,
195    )
196    signature_algorithm = models.TextField(
197        choices=(
198            (RSA_SHA1, _("RSA-SHA1")),
199            (RSA_SHA256, _("RSA-SHA256")),
200            (RSA_SHA384, _("RSA-SHA384")),
201            (RSA_SHA512, _("RSA-SHA512")),
202            (ECDSA_SHA1, _("ECDSA-SHA1")),
203            (ECDSA_SHA256, _("ECDSA-SHA256")),
204            (ECDSA_SHA384, _("ECDSA-SHA384")),
205            (ECDSA_SHA512, _("ECDSA-SHA512")),
206            (DSA_SHA1, _("DSA-SHA1")),
207        ),
208        default=RSA_SHA256,
209    )
210
211    signed_assertion = models.BooleanField(default=True)
212    signed_response = models.BooleanField(default=False)
213
214    @property
215    def component(self) -> str:
216        return "ak-source-saml-form"
217
218    @property
219    def serializer(self) -> type[Serializer]:
220        from authentik.sources.saml.api.source import SAMLSourceSerializer
221
222        return SAMLSourceSerializer
223
224    @property
225    def property_mapping_type(self) -> type[PropertyMapping]:
226        return SAMLSourcePropertyMapping
227
228    def get_base_user_properties(self, root: _Element, assertion: _Element, name_id: Any, **kwargs):
229        attributes = {}
230        if assertion is None:
231            raise ValueError("Assertion element not found")
232        attribute_statement = assertion.find(f"{{{NS_SAML_ASSERTION}}}AttributeStatement")
233        if attribute_statement is None:
234            raise ValueError("Attribute statement element not found")
235        # Get all attributes and their values into a dict
236        for attribute in attribute_statement.iterchildren():
237            key = attribute.attrib["Name"]
238            attributes.setdefault(key, [])
239            for value in attribute.iterchildren():
240                attributes[key].append(get_element_text(value))
241        if SAML_ATTRIBUTES_GROUP in attributes:
242            attributes["groups"] = attributes[SAML_ATTRIBUTES_GROUP]
243            del attributes[SAML_ATTRIBUTES_GROUP]
244        # Flatten all lists in the dict
245        for key, value in attributes.items():
246            if key == "groups":
247                continue
248            attributes[key] = BaseEvaluator.expr_flatten(value)
249        attributes["username"] = get_element_text(name_id)
250
251        return attributes
252
253    def get_base_group_properties(self, group_id: str, **kwargs):
254        return {
255            "name": group_id,
256        }
257
258    def get_issuer(self, request: HttpRequest) -> str:
259        """Get Source's Issuer, falling back to our Metadata URL if none is set"""
260        if not self.issuer_override:
261            return request.build_absolute_uri(
262                reverse("authentik_sources_saml:metadata", kwargs={"source_slug": self.slug})
263            )
264        return self.issuer_override
265
266    @property
267    def icon_url(self) -> str:
268        icon = super().icon_url
269        if not icon:
270            return static("authentik/sources/saml/light.png")
271        return icon
272
273    def ui_login_button(self, request: HttpRequest) -> UILoginButton:
274        return UILoginButton(
275            challenge=RedirectChallenge(
276                data={
277                    "to": reverse(
278                        "authentik_sources_saml:login",
279                        kwargs={"source_slug": self.slug},
280                    ),
281                }
282            ),
283            name=self.name,
284            icon_url=self.get_icon_url(request, use_cache=False) or self.icon_url,
285            icon_themed_urls=self.get_icon_themed_urls(request, use_cache=False),
286            promoted=self.promoted,
287        )
288
289    def ui_user_settings(self) -> UserSettingSerializer | None:
290        return UserSettingSerializer(
291            data={
292                "title": self.name,
293                "component": "ak-user-settings-source-saml",
294                "configure_url": reverse(
295                    "authentik_sources_saml:login",
296                    kwargs={"source_slug": self.slug},
297                ),
298                "icon_url": self.icon_url,
299                "icon_themed_urls": self.icon_themed_urls,
300            }
301        )
302
303    def __str__(self):
304        return f"SAML Source {self.name}"
305
306    class Meta:
307        verbose_name = _("SAML Source")
308        verbose_name_plural = _("SAML Sources")
309
310
311class SAMLSourcePropertyMapping(PropertyMapping):
312    """Map SAML properties to User or Group object attributes"""
313
314    expression_allowed_types = [dict]
315
316    @property
317    def component(self) -> str:
318        return "ak-property-mapping-source-saml-form"
319
320    @property
321    def serializer(self) -> type[Serializer]:
322        from authentik.sources.saml.api.property_mappings import SAMLSourcePropertyMappingSerializer
323
324        return SAMLSourcePropertyMappingSerializer
325
326    class Meta:
327        verbose_name = _("SAML Source Property Mapping")
328        verbose_name_plural = _("SAML Source Property Mappings")
329
330
331class UserSAMLSourceConnection(UserSourceConnection):
332    """Connection to configured SAML Sources."""
333
334    @property
335    def serializer(self) -> Serializer:
336        from authentik.sources.saml.api.source_connection import UserSAMLSourceConnectionSerializer
337
338        return UserSAMLSourceConnectionSerializer
339
340    class Meta:
341        verbose_name = _("User SAML Source Connection")
342        verbose_name_plural = _("User SAML Source Connections")
343
344
345class GroupSAMLSourceConnection(GroupSourceConnection):
346    """Group-source connection"""
347
348    @property
349    def serializer(self) -> type[Serializer]:
350        from authentik.sources.saml.api.source_connection import (
351            GroupSAMLSourceConnectionSerializer,
352        )
353
354        return GroupSAMLSourceConnectionSerializer
355
356    class Meta:
357        verbose_name = _("Group SAML Source Connection")
358        verbose_name_plural = _("Group SAML Source Connections")
class SAMLBindingTypes(django.db.models.enums.TextChoices):
55class SAMLBindingTypes(models.TextChoices):
56    """SAML Binding types"""
57
58    REDIRECT = "REDIRECT", _("Redirect Binding")
59    POST = "POST", _("POST Binding")
60    POST_AUTO = "POST_AUTO", _("POST Binding with auto-confirmation")
61
62    @property
63    def uri(self) -> str:
64        """Convert database field to URI"""
65        return {
66            SAMLBindingTypes.POST: SAML_BINDING_POST,
67            SAMLBindingTypes.POST_AUTO: SAML_BINDING_POST,
68            SAMLBindingTypes.REDIRECT: SAML_BINDING_REDIRECT,
69        }[self]

SAML Binding types

uri: str
62    @property
63    def uri(self) -> str:
64        """Convert database field to URI"""
65        return {
66            SAMLBindingTypes.POST: SAML_BINDING_POST,
67            SAMLBindingTypes.POST_AUTO: SAML_BINDING_POST,
68            SAMLBindingTypes.REDIRECT: SAML_BINDING_REDIRECT,
69        }[self]

Convert database field to URI

class SAMLNameIDPolicy(django.db.models.enums.TextChoices):
72class SAMLNameIDPolicy(models.TextChoices):
73    """SAML NameID Policies"""
74
75    EMAIL = SAML_NAME_ID_FORMAT_EMAIL
76    PERSISTENT = SAML_NAME_ID_FORMAT_PERSISTENT
77    X509 = SAML_NAME_ID_FORMAT_X509
78    WINDOWS = SAML_NAME_ID_FORMAT_WINDOWS
79    TRANSIENT = SAML_NAME_ID_FORMAT_TRANSIENT
80    UNSPECIFIED = SAML_NAME_ID_FORMAT_UNSPECIFIED

SAML NameID Policies

class SAMLSource(authentik.core.models.Source):
 83class SAMLSource(Source):
 84    """Authenticate using an external SAML Identity Provider."""
 85
 86    pre_authentication_flow = models.ForeignKey(
 87        Flow,
 88        on_delete=models.CASCADE,
 89        help_text=_("Flow used before authentication."),
 90        related_name="source_pre_authentication",
 91    )
 92
 93    issuer_override = models.TextField(
 94        blank=True,
 95        default="",
 96        help_text=_("Also known as Entity ID. Defaults to the Metadata URL."),
 97    )
 98
 99    sso_url = models.TextField(
100        validators=[DomainlessURLValidator(schemes=("http", "https"))],
101        verbose_name=_("SSO URL"),
102        help_text=_("URL that the initial Login request is sent to."),
103    )
104    slo_url = models.TextField(
105        validators=[DomainlessURLValidator(schemes=("http", "https"))],
106        default=None,
107        blank=True,
108        null=True,
109        verbose_name=_("SLO URL"),
110        help_text=_("Optional URL if your IDP supports Single-Logout."),
111    )
112
113    allow_idp_initiated = models.BooleanField(
114        default=False,
115        help_text=_(
116            "Allows authentication flows initiated by the IdP. This can be a security risk, "
117            "as no validation of the request ID is done."
118        ),
119    )
120    force_authn = models.BooleanField(
121        default=False,
122        help_text=_(
123            "When enabled, the IdP will re-authenticate the user even if a session exists."
124        ),
125    )
126    name_id_policy = models.TextField(
127        choices=SAMLNameIDPolicy.choices,
128        default=SAMLNameIDPolicy.PERSISTENT,
129        help_text=_(
130            "Format of the NameID Policy sent to the IdP. Select Unspecified to let the IdP "
131            "choose the format of the NameID it returns."
132        ),
133    )
134    binding_type = models.CharField(
135        max_length=100,
136        choices=SAMLBindingTypes.choices,
137        default=SAMLBindingTypes.REDIRECT,
138    )
139
140    temporary_user_delete_after = models.TextField(
141        default="days=1",
142        verbose_name=_("Delete temporary users after"),
143        validators=[timedelta_string_validator],
144        help_text=_(
145            "Time offset when temporary users should be deleted. This only applies if your IDP "
146            "uses the NameID Format 'transient', and the user doesn't log out manually. "
147            "(Format: hours=1;minutes=2;seconds=3)."
148        ),
149    )
150
151    verification_kp = models.ForeignKey(
152        CertificateKeyPair,
153        default=None,
154        null=True,
155        blank=True,
156        help_text=_(
157            "When selected, incoming assertion's Signatures will be validated against this "
158            "certificate. To allow unsigned Requests, leave on default."
159        ),
160        on_delete=models.SET_NULL,
161        verbose_name=_("Verification Certificate"),
162        related_name="+",
163    )
164    signing_kp = models.ForeignKey(
165        CertificateKeyPair,
166        default=None,
167        null=True,
168        blank=True,
169        help_text=_("Keypair used to sign outgoing Responses going to the Identity Provider."),
170        on_delete=models.SET_NULL,
171        verbose_name=_("Signing Keypair"),
172    )
173    encryption_kp = models.ForeignKey(
174        CertificateKeyPair,
175        default=None,
176        null=True,
177        blank=True,
178        help_text=_(
179            "When selected, incoming assertions are encrypted by the IdP using the public "
180            "key of the encryption keypair. The assertion is decrypted by the SP using the "
181            "the private key."
182        ),
183        on_delete=models.SET_NULL,
184        verbose_name=_("Encryption Keypair"),
185        related_name="+",
186    )
187
188    digest_algorithm = models.TextField(
189        choices=(
190            (SHA1, _("SHA1")),
191            (SHA256, _("SHA256")),
192            (SHA384, _("SHA384")),
193            (SHA512, _("SHA512")),
194        ),
195        default=SHA256,
196    )
197    signature_algorithm = models.TextField(
198        choices=(
199            (RSA_SHA1, _("RSA-SHA1")),
200            (RSA_SHA256, _("RSA-SHA256")),
201            (RSA_SHA384, _("RSA-SHA384")),
202            (RSA_SHA512, _("RSA-SHA512")),
203            (ECDSA_SHA1, _("ECDSA-SHA1")),
204            (ECDSA_SHA256, _("ECDSA-SHA256")),
205            (ECDSA_SHA384, _("ECDSA-SHA384")),
206            (ECDSA_SHA512, _("ECDSA-SHA512")),
207            (DSA_SHA1, _("DSA-SHA1")),
208        ),
209        default=RSA_SHA256,
210    )
211
212    signed_assertion = models.BooleanField(default=True)
213    signed_response = models.BooleanField(default=False)
214
215    @property
216    def component(self) -> str:
217        return "ak-source-saml-form"
218
219    @property
220    def serializer(self) -> type[Serializer]:
221        from authentik.sources.saml.api.source import SAMLSourceSerializer
222
223        return SAMLSourceSerializer
224
225    @property
226    def property_mapping_type(self) -> type[PropertyMapping]:
227        return SAMLSourcePropertyMapping
228
229    def get_base_user_properties(self, root: _Element, assertion: _Element, name_id: Any, **kwargs):
230        attributes = {}
231        if assertion is None:
232            raise ValueError("Assertion element not found")
233        attribute_statement = assertion.find(f"{{{NS_SAML_ASSERTION}}}AttributeStatement")
234        if attribute_statement is None:
235            raise ValueError("Attribute statement element not found")
236        # Get all attributes and their values into a dict
237        for attribute in attribute_statement.iterchildren():
238            key = attribute.attrib["Name"]
239            attributes.setdefault(key, [])
240            for value in attribute.iterchildren():
241                attributes[key].append(get_element_text(value))
242        if SAML_ATTRIBUTES_GROUP in attributes:
243            attributes["groups"] = attributes[SAML_ATTRIBUTES_GROUP]
244            del attributes[SAML_ATTRIBUTES_GROUP]
245        # Flatten all lists in the dict
246        for key, value in attributes.items():
247            if key == "groups":
248                continue
249            attributes[key] = BaseEvaluator.expr_flatten(value)
250        attributes["username"] = get_element_text(name_id)
251
252        return attributes
253
254    def get_base_group_properties(self, group_id: str, **kwargs):
255        return {
256            "name": group_id,
257        }
258
259    def get_issuer(self, request: HttpRequest) -> str:
260        """Get Source's Issuer, falling back to our Metadata URL if none is set"""
261        if not self.issuer_override:
262            return request.build_absolute_uri(
263                reverse("authentik_sources_saml:metadata", kwargs={"source_slug": self.slug})
264            )
265        return self.issuer_override
266
267    @property
268    def icon_url(self) -> str:
269        icon = super().icon_url
270        if not icon:
271            return static("authentik/sources/saml/light.png")
272        return icon
273
274    def ui_login_button(self, request: HttpRequest) -> UILoginButton:
275        return UILoginButton(
276            challenge=RedirectChallenge(
277                data={
278                    "to": reverse(
279                        "authentik_sources_saml:login",
280                        kwargs={"source_slug": self.slug},
281                    ),
282                }
283            ),
284            name=self.name,
285            icon_url=self.get_icon_url(request, use_cache=False) or self.icon_url,
286            icon_themed_urls=self.get_icon_themed_urls(request, use_cache=False),
287            promoted=self.promoted,
288        )
289
290    def ui_user_settings(self) -> UserSettingSerializer | None:
291        return UserSettingSerializer(
292            data={
293                "title": self.name,
294                "component": "ak-user-settings-source-saml",
295                "configure_url": reverse(
296                    "authentik_sources_saml:login",
297                    kwargs={"source_slug": self.slug},
298                ),
299                "icon_url": self.icon_url,
300                "icon_themed_urls": self.icon_themed_urls,
301            }
302        )
303
304    def __str__(self):
305        return f"SAML Source {self.name}"
306
307    class Meta:
308        verbose_name = _("SAML Source")
309        verbose_name_plural = _("SAML Sources")

Authenticate using an external SAML Identity Provider.

pre_authentication_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.

def issuer_override(unknown):

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

def sso_url(unknown):

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

def slo_url(unknown):

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

def allow_idp_initiated(unknown):

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

def force_authn(unknown):

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

def name_id_policy(unknown):

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

def binding_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 temporary_user_delete_after(unknown):

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

verification_kp

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.

signing_kp

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_kp

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 digest_algorithm(unknown):

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

def signature_algorithm(unknown):

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

def signed_assertion(unknown):

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

def signed_response(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
215    @property
216    def component(self) -> str:
217        return "ak-source-saml-form"

Return component used to edit this object

serializer: type[rest_framework.serializers.Serializer]
219    @property
220    def serializer(self) -> type[Serializer]:
221        from authentik.sources.saml.api.source import SAMLSourceSerializer
222
223        return SAMLSourceSerializer

Get serializer for this model

property_mapping_type: type[authentik.core.models.PropertyMapping]
225    @property
226    def property_mapping_type(self) -> type[PropertyMapping]:
227        return SAMLSourcePropertyMapping

Return property mapping type used by this object

def get_base_user_properties( self, root: lxml.etree._Element, assertion: lxml.etree._Element, name_id: Any, **kwargs):
229    def get_base_user_properties(self, root: _Element, assertion: _Element, name_id: Any, **kwargs):
230        attributes = {}
231        if assertion is None:
232            raise ValueError("Assertion element not found")
233        attribute_statement = assertion.find(f"{{{NS_SAML_ASSERTION}}}AttributeStatement")
234        if attribute_statement is None:
235            raise ValueError("Attribute statement element not found")
236        # Get all attributes and their values into a dict
237        for attribute in attribute_statement.iterchildren():
238            key = attribute.attrib["Name"]
239            attributes.setdefault(key, [])
240            for value in attribute.iterchildren():
241                attributes[key].append(get_element_text(value))
242        if SAML_ATTRIBUTES_GROUP in attributes:
243            attributes["groups"] = attributes[SAML_ATTRIBUTES_GROUP]
244            del attributes[SAML_ATTRIBUTES_GROUP]
245        # Flatten all lists in the dict
246        for key, value in attributes.items():
247            if key == "groups":
248                continue
249            attributes[key] = BaseEvaluator.expr_flatten(value)
250        attributes["username"] = get_element_text(name_id)
251
252        return attributes

Get base properties for a user to build final properties upon.

def get_base_group_properties(self, group_id: str, **kwargs):
254    def get_base_group_properties(self, group_id: str, **kwargs):
255        return {
256            "name": group_id,
257        }

Get base properties for a group to build final properties upon.

def get_issuer(self, request: django.http.request.HttpRequest) -> str:
259    def get_issuer(self, request: HttpRequest) -> str:
260        """Get Source's Issuer, falling back to our Metadata URL if none is set"""
261        if not self.issuer_override:
262            return request.build_absolute_uri(
263                reverse("authentik_sources_saml:metadata", kwargs={"source_slug": self.slug})
264            )
265        return self.issuer_override

Get Source's Issuer, falling back to our Metadata URL if none is set

icon_url: str
267    @property
268    def icon_url(self) -> str:
269        icon = super().icon_url
270        if not icon:
271            return static("authentik/sources/saml/light.png")
272        return icon

Get the URL to the source icon

def ui_login_button( self, request: django.http.request.HttpRequest) -> authentik.core.types.UILoginButton:
274    def ui_login_button(self, request: HttpRequest) -> UILoginButton:
275        return UILoginButton(
276            challenge=RedirectChallenge(
277                data={
278                    "to": reverse(
279                        "authentik_sources_saml:login",
280                        kwargs={"source_slug": self.slug},
281                    ),
282                }
283            ),
284            name=self.name,
285            icon_url=self.get_icon_url(request, use_cache=False) or self.icon_url,
286            icon_themed_urls=self.get_icon_themed_urls(request, use_cache=False),
287            promoted=self.promoted,
288        )

If source uses a http-based flow, return UI Information about the login button. If source doesn't use http-based flow, return None.

def ui_user_settings(self) -> authentik.core.types.UserSettingSerializer | None:
290    def ui_user_settings(self) -> UserSettingSerializer | None:
291        return UserSettingSerializer(
292            data={
293                "title": self.name,
294                "component": "ak-user-settings-source-saml",
295                "configure_url": reverse(
296                    "authentik_sources_saml:login",
297                    kwargs={"source_slug": self.slug},
298                ),
299                "icon_url": self.icon_url,
300                "icon_themed_urls": self.icon_themed_urls,
301            }
302        )

Entrypoint to integrate with User settings. Can either return None if no user settings are available, or UserSettingSerializer.

pre_authentication_flow_id
def get_name_id_policy_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_binding_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.

verification_kp_id
signing_kp_id
encryption_kp_id
def get_digest_algorithm_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_signature_algorithm_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.

source_ptr_id
source_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.

class SAMLSource.DoesNotExist(authentik.core.models.Source.DoesNotExist):

The requested object does not exist

class SAMLSource.MultipleObjectsReturned(authentik.core.models.Source.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class SAMLSourcePropertyMapping(authentik.core.models.PropertyMapping):
312class SAMLSourcePropertyMapping(PropertyMapping):
313    """Map SAML properties to User or Group object attributes"""
314
315    expression_allowed_types = [dict]
316
317    @property
318    def component(self) -> str:
319        return "ak-property-mapping-source-saml-form"
320
321    @property
322    def serializer(self) -> type[Serializer]:
323        from authentik.sources.saml.api.property_mappings import SAMLSourcePropertyMappingSerializer
324
325        return SAMLSourcePropertyMappingSerializer
326
327    class Meta:
328        verbose_name = _("SAML Source Property Mapping")
329        verbose_name_plural = _("SAML Source Property Mappings")

Map SAML properties to User or Group object attributes

expression_allowed_types = [<class 'dict'>]
component: str
317    @property
318    def component(self) -> str:
319        return "ak-property-mapping-source-saml-form"

Return component used to edit this object

serializer: type[rest_framework.serializers.Serializer]
321    @property
322    def serializer(self) -> type[Serializer]:
323        from authentik.sources.saml.api.property_mappings import SAMLSourcePropertyMappingSerializer
324
325        return SAMLSourcePropertyMappingSerializer

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.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class UserSAMLSourceConnection(authentik.core.models.UserSourceConnection):
332class UserSAMLSourceConnection(UserSourceConnection):
333    """Connection to configured SAML Sources."""
334
335    @property
336    def serializer(self) -> Serializer:
337        from authentik.sources.saml.api.source_connection import UserSAMLSourceConnectionSerializer
338
339        return UserSAMLSourceConnectionSerializer
340
341    class Meta:
342        verbose_name = _("User SAML Source Connection")
343        verbose_name_plural = _("User SAML Source Connections")

Connection to configured SAML Sources.

serializer: rest_framework.serializers.Serializer
335    @property
336    def serializer(self) -> Serializer:
337        from authentik.sources.saml.api.source_connection import UserSAMLSourceConnectionSerializer
338
339        return UserSAMLSourceConnectionSerializer

Get serializer for this model

usersourceconnection_ptr_id
usersourceconnection_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.

class UserSAMLSourceConnection.DoesNotExist(authentik.core.models.UserSourceConnection.DoesNotExist):

The requested object does not exist

class UserSAMLSourceConnection.MultipleObjectsReturned(authentik.core.models.UserSourceConnection.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class GroupSAMLSourceConnection(authentik.core.models.GroupSourceConnection):
346class GroupSAMLSourceConnection(GroupSourceConnection):
347    """Group-source connection"""
348
349    @property
350    def serializer(self) -> type[Serializer]:
351        from authentik.sources.saml.api.source_connection import (
352            GroupSAMLSourceConnectionSerializer,
353        )
354
355        return GroupSAMLSourceConnectionSerializer
356
357    class Meta:
358        verbose_name = _("Group SAML Source Connection")
359        verbose_name_plural = _("Group SAML Source Connections")

Group-source connection

serializer: type[rest_framework.serializers.Serializer]
349    @property
350    def serializer(self) -> type[Serializer]:
351        from authentik.sources.saml.api.source_connection import (
352            GroupSAMLSourceConnectionSerializer,
353        )
354
355        return GroupSAMLSourceConnectionSerializer

Get serializer for this model

groupsourceconnection_ptr_id
groupsourceconnection_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.

class GroupSAMLSourceConnection.DoesNotExist(authentik.core.models.GroupSourceConnection.DoesNotExist):

The requested object does not exist

class GroupSAMLSourceConnection.MultipleObjectsReturned(authentik.core.models.GroupSourceConnection.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.