authentik.sources.ldap.models

authentik LDAP Models

  1"""authentik LDAP Models"""
  2
  3from os import chmod
  4from os.path import dirname, exists
  5from shutil import rmtree
  6from ssl import CERT_REQUIRED
  7from tempfile import NamedTemporaryFile, mkdtemp
  8from typing import TYPE_CHECKING, Any
  9from urllib.parse import urlparse
 10
 11import pglock
 12from django.db import connection, models
 13from django.templatetags.static import static
 14from django.utils.translation import gettext_lazy as _
 15from rest_framework.serializers import Serializer
 16from structlog.stdlib import get_logger
 17
 18from authentik.core.models import (
 19    Group,
 20    GroupSourceConnection,
 21    PropertyMapping,
 22    UserSourceConnection,
 23)
 24from authentik.crypto.models import CertificateKeyPair
 25from authentik.lib.config import CONFIG, advisory_lock_db_alias
 26from authentik.lib.models import DomainlessURLValidator
 27from authentik.lib.sync.incoming.models import IncomingSyncSource
 28from authentik.lib.utils.time import fqdn_rand
 29from authentik.tasks.schedules.common import ScheduleSpec
 30
 31if TYPE_CHECKING:
 32    from ldap3 import Connection, Server, ServerPool
 33
 34LDAP_TIMEOUT = 15
 35LDAP_UNIQUENESS = "ldap_uniq"
 36"""Deprecated, don't use"""
 37LDAP_DISTINGUISHED_NAME = "distinguishedName"
 38LOGGER = get_logger()
 39
 40
 41def flatten(value: Any) -> Any:
 42    """Flatten `value` if its a list, set or tuple"""
 43    if isinstance(value, list | set | tuple):
 44        if len(value) < 1:
 45            return None
 46        if isinstance(value, set):
 47            return value.pop()
 48        return value[0]
 49    return value
 50
 51
 52class MultiURLValidator(DomainlessURLValidator):
 53    """Same as DomainlessURLValidator but supports multiple URLs separated with a comma."""
 54
 55    def __call__(self, value: str):
 56        if "," in value:
 57            for url in value.split(","):
 58                super().__call__(url)
 59        else:
 60            super().__call__(value)
 61
 62
 63class LDAPSourceBindMethod(models.TextChoices):
 64    """Authentication method for LDAP service connections."""
 65
 66    SIMPLE = "simple", _("Simple or anonymous bind")
 67    SASL_EXTERNAL = "sasl_external", _("SASL EXTERNAL")
 68
 69
 70class LDAPSource(IncomingSyncSource):
 71    """Federate LDAP Directory with authentik, or create new accounts in LDAP."""
 72
 73    server_uri = models.TextField(
 74        validators=[MultiURLValidator(schemes=["ldap", "ldaps"])],
 75        verbose_name=_("Server URI"),
 76    )
 77    peer_certificate = models.ForeignKey(
 78        CertificateKeyPair,
 79        on_delete=models.SET_DEFAULT,
 80        default=None,
 81        null=True,
 82        related_name="ldap_peer_certificates",
 83        help_text=_(
 84            "Optionally verify the LDAP Server's Certificate against the CA Chain in this keypair."
 85        ),
 86    )
 87    client_certificate = models.ForeignKey(
 88        CertificateKeyPair,
 89        on_delete=models.SET_DEFAULT,
 90        default=None,
 91        null=True,
 92        related_name="ldap_client_certificates",
 93        help_text=_("Client certificate to authenticate against the LDAP Server's Certificate."),
 94    )
 95
 96    bind_cn = models.TextField(verbose_name=_("Bind CN"), blank=True)
 97    bind_password = models.TextField(blank=True)
 98    service_bind_method = models.TextField(
 99        choices=LDAPSourceBindMethod,
100        default=LDAPSourceBindMethod.SIMPLE,
101        help_text=_("Authentication method used for LDAP synchronization and writeback."),
102    )
103    start_tls = models.BooleanField(default=False, verbose_name=_("Enable Start TLS"))
104    sni = models.BooleanField(default=False, verbose_name=_("Use Server URI for SNI verification"))
105
106    base_dn = models.TextField(verbose_name=_("Base DN"))
107    additional_user_dn = models.TextField(
108        help_text=_("Prepended to Base DN for User-queries."),
109        verbose_name=_("Addition User DN"),
110        blank=True,
111    )
112    additional_group_dn = models.TextField(
113        help_text=_("Prepended to Base DN for Group-queries."),
114        verbose_name=_("Addition Group DN"),
115        blank=True,
116    )
117
118    user_object_filter = models.TextField(
119        default="(objectClass=person)",
120        help_text=_("Consider Objects matching this filter to be Users."),
121    )
122    user_membership_attribute = models.TextField(
123        default=LDAP_DISTINGUISHED_NAME,
124        help_text=_("Attribute which matches the value of `group_membership_field`."),
125    )
126    group_membership_field = models.TextField(
127        default="member", help_text=_("Field which contains members of a group.")
128    )
129    group_object_filter = models.TextField(
130        default="(objectClass=group)",
131        help_text=_("Consider Objects matching this filter to be Groups."),
132    )
133    object_uniqueness_field = models.TextField(
134        default="objectSid", help_text=_("Field which contains a unique Identifier.")
135    )
136
137    password_login_update_internal_password = models.BooleanField(
138        default=False,
139        help_text=_("Update internal authentik password when login succeeds with LDAP"),
140    )
141
142    sync_users = models.BooleanField(default=True)
143    sync_users_password = models.BooleanField(
144        default=True,
145        help_text=_(
146            "When a user changes their password, sync it back to LDAP. "
147            "This can only be enabled on a single LDAP source."
148        ),
149    )
150    sync_groups = models.BooleanField(default=True)
151    sync_parent_group = models.ForeignKey(
152        Group, blank=True, null=True, default=None, on_delete=models.SET_DEFAULT
153    )
154
155    sync_group_hierarchy = models.BooleanField(
156        default=False, help_text=_("Sync group parentage/hierarchy from LDAP directories.")
157    )
158
159    lookup_groups_from_user = models.BooleanField(
160        default=False,
161        help_text=_(
162            "Lookup group membership based on a user attribute instead of a group attribute. "
163            "This allows nested group resolution on systems like FreeIPA and Active Directory"
164        ),
165    )
166
167    delete_not_found_objects = models.BooleanField(
168        default=False,
169        help_text=_(
170            "Delete authentik users and groups which were previously supplied by this source, "
171            "but are now missing from it."
172        ),
173    )
174
175    @property
176    def component(self) -> str:
177        return "ak-source-ldap-form"
178
179    @property
180    def serializer(self) -> type[Serializer]:
181        from authentik.sources.ldap.api.sources import LDAPSourceSerializer
182
183        return LDAPSourceSerializer
184
185    @property
186    def schedule_specs(self) -> list[ScheduleSpec]:
187        from authentik.sources.ldap.tasks import ldap_connectivity_check, ldap_sync
188
189        return [
190            ScheduleSpec(
191                actor=ldap_sync,
192                uid=self.slug,
193                args=(self.pk,),
194                crontab=f"{fqdn_rand('ldap_sync/' + str(self.pk))} */2 * * *",
195                send_on_save=True,
196            ),
197            ScheduleSpec(
198                actor=ldap_connectivity_check,
199                uid=self.slug,
200                args=(self.pk,),
201                crontab=f"{fqdn_rand('ldap_connectivity_check/' + str(self.pk))} * * * *",
202                send_on_save=True,
203            ),
204        ]
205
206    @property
207    def property_mapping_type(self) -> type[PropertyMapping]:
208        from authentik.sources.ldap.models import LDAPSourcePropertyMapping
209
210        return LDAPSourcePropertyMapping
211
212    def update_properties_with_uniqueness_field(self, properties, dn, ldap, **kwargs):
213        properties.setdefault("attributes", {})[LDAP_DISTINGUISHED_NAME] = dn
214        # TODO: Remove after 2026.5, still stored for legacy
215        if self.object_uniqueness_field in ldap:
216            properties["attributes"][LDAP_UNIQUENESS] = flatten(
217                ldap.get(self.object_uniqueness_field)
218            )
219        return properties
220
221    def get_base_user_properties(self, **kwargs):
222        return self.update_properties_with_uniqueness_field({}, **kwargs)
223
224    def get_base_group_properties(self, **kwargs):
225        return self.update_properties_with_uniqueness_field(
226            {
227                "parent": self.sync_parent_group,
228            },
229            **kwargs,
230        )
231
232    @property
233    def icon_url(self) -> str:
234        return static("authentik/sources/ldap/light.svg")
235
236    def server(self, **kwargs) -> ServerPool:
237        """Get LDAP Server/ServerPool"""
238        # ldap3 is only imported when an LDAP source is used
239        from ldap3 import ALL, RANDOM, Server, ServerPool, Tls
240
241        servers = []
242        tls_kwargs = {}
243        if self.peer_certificate:
244            tls_kwargs["ca_certs_data"] = self.peer_certificate.certificate_data
245            tls_kwargs["validate"] = CERT_REQUIRED
246        if self.client_certificate:
247            temp_dir = mkdtemp()
248            with NamedTemporaryFile(mode="w", delete=False, dir=temp_dir) as temp_cert:
249                temp_cert.write(self.client_certificate.certificate_data)
250                certificate_file = temp_cert.name
251                chmod(certificate_file, 0o600)
252            with NamedTemporaryFile(mode="w", delete=False, dir=temp_dir) as temp_key:
253                temp_key.write(self.client_certificate.key_data)
254                private_key_file = temp_key.name
255                chmod(private_key_file, 0o600)
256            tls_kwargs["local_private_key_file"] = private_key_file
257            tls_kwargs["local_certificate_file"] = certificate_file
258        if ciphers := CONFIG.get("ldap.tls.ciphers", None):
259            tls_kwargs["ciphers"] = ciphers.strip()
260        server_kwargs = {
261            "get_info": ALL,
262            "connect_timeout": LDAP_TIMEOUT,
263        }
264        server_kwargs.update(kwargs)
265        for server_uri in self.server_uri.split(","):
266            server = Server(server_uri.strip(), **server_kwargs)
267            # The TLS SNI server name must be a bare hostname. ldap3 has already
268            # parsed the scheme and port out of the URI into `server.host`;
269            # passing the raw URI (e.g. `ldaps://host`) as the SNI name breaks
270            # the handshake against SNI-strict servers. See #7756.
271            server.tls = Tls(**tls_kwargs, sni=server.host if self.sni else None)
272            servers.append(server)
273        return ServerPool(servers, RANDOM, active=5, exhaust=True)
274
275    def connection(
276        self,
277        server: Server | None = None,
278        server_kwargs: dict | None = None,
279        connection_kwargs: dict | None = None,
280    ) -> Connection:
281        """Get a service connection for synchronization, searches, and writeback."""
282        from ldap3 import EXTERNAL, SASL
283
284        connection_kwargs = dict(connection_kwargs or {})
285        if self.service_bind_method == LDAPSourceBindMethod.SASL_EXTERNAL:
286            self._validate_sasl_external_configuration()
287            connection_kwargs.pop("user", None)
288            connection_kwargs.pop("password", None)
289            connection_kwargs.update(
290                authentication=SASL,
291                sasl_mechanism=EXTERNAL,
292                sasl_credentials="",
293            )
294        else:
295            connection_kwargs.setdefault("user", self.bind_cn)
296            connection_kwargs.setdefault("password", self.bind_password)
297        return self._connect_and_bind(server, server_kwargs, connection_kwargs)
298
299    def connection_as_user(self, user: str, password: str) -> Connection:
300        """Bind as an LDAP user to verify their submitted password."""
301        from ldap3 import SIMPLE
302
303        return self._connect_and_bind(
304            connection_kwargs={
305                "user": user,
306                "password": password,
307                "authentication": SIMPLE,
308            }
309        )
310
311    def _validate_sasl_external_configuration(self) -> None:
312        """Ensure SASL EXTERNAL has a certificate-backed TLS transport."""
313        from ldap3.core.exceptions import LDAPConfigurationError
314
315        if not self.client_certificate or not self.client_certificate.key_data:
316            raise LDAPConfigurationError(
317                "SASL EXTERNAL requires a client certificate with a private key"
318            )
319        schemes = {urlparse(uri.strip()).scheme for uri in self.server_uri.split(",")}
320        expected_schemes = {"ldap"} if self.start_tls else {"ldaps"}
321        if schemes != expected_schemes:
322            raise LDAPConfigurationError(
323                "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without StartTLS"
324            )
325
326    def _connect_and_bind(
327        self,
328        server: Server | None = None,
329        server_kwargs: dict | None = None,
330        connection_kwargs: dict | None = None,
331    ) -> Connection:
332        """Create, secure, and bind an LDAP connection."""
333        from ldap3 import ALL, NONE, Connection
334        from ldap3.core.exceptions import (
335            LDAPAdminLimitExceededResult,
336            LDAPAttributeError,
337            LDAPException,
338            LDAPInsufficientAccessRightsResult,
339            LDAPSchemaError,
340        )
341
342        server_kwargs = server_kwargs or {}
343        connection_kwargs = connection_kwargs or {}
344        conn = Connection(
345            server or self.server(**server_kwargs),
346            raise_exceptions=True,
347            receive_timeout=LDAP_TIMEOUT,
348            **connection_kwargs,
349        )
350
351        if self.start_tls:
352            LOGGER.debug("Connection StartTLS", source=self)
353            conn.start_tls(read_server_info=False)
354        try:
355            successful = conn.bind()
356            if successful:
357                return conn
358        except (
359            LDAPSchemaError,
360            LDAPInsufficientAccessRightsResult,
361            LDAPAdminLimitExceededResult,
362            LDAPAttributeError,
363        ) as exc:
364            # Schema error or rate limit during schema fetch, retry without schema info
365            # See https://github.com/goauthentik/authentik/issues/4590
366            # See also https://github.com/goauthentik/authentik/issues/3399
367            # LDAPAdminLimitExceededResult: Google Secure LDAP rate-limits schema queries
368            # LDAPAttributeError: Google Secure LDAP returns unsupported attrs in schema
369            if server_kwargs.get("get_info", ALL) == NONE:
370                LOGGER.warning("Failed to connect after schema downgrade", source=self, exc=exc)
371                raise exc
372            LOGGER.warning("Downgrading connection to no schema info", source=self, exc=exc)
373            server_kwargs["get_info"] = NONE
374            return self._connect_and_bind(server, server_kwargs, connection_kwargs)
375        finally:
376            if conn.server.tls.certificate_file is not None and exists(
377                conn.server.tls.certificate_file
378            ):
379                rmtree(dirname(conn.server.tls.certificate_file))
380        raise LDAPException("Failed to bind")
381
382    @property
383    def sync_lock(self) -> pglock.advisory:
384        """Postgres lock for syncing LDAP to prevent multiple parallel syncs happening"""
385        return pglock.advisory(
386            lock_id=f"goauthentik.io/{connection.schema_name}/sources/ldap/sync/{self.slug}",
387            timeout=0,
388            side_effect=pglock.Return,
389            using=advisory_lock_db_alias(),
390        )
391
392    def get_ldap_server_info(self, srv: Server) -> dict[str, str]:
393        info = {
394            "vendor": _("N/A"),
395            "version": _("N/A"),
396        }
397        if srv.info:
398            info["vendor"] = str(flatten(srv.info.vendor_name))
399            info["version"] = str(flatten(srv.info.vendor_version))
400        return info
401
402    def check_connection(self) -> dict[str, dict[str, str]]:
403        """Check LDAP Connection"""
404        from ldap3.core.exceptions import LDAPException
405
406        servers = self.server()
407        server_info = {}
408        # Check each individual server
409        for server in servers.servers:
410            server: Server
411            try:
412                conn = self.connection(server=server)
413                server_info[server.host] = {
414                    "status": "ok",
415                    **self.get_ldap_server_info(conn.server),
416                }
417            except LDAPException as exc:
418                server_info[server.host] = {
419                    "status": str(exc),
420                }
421        # Check server pool
422        try:
423            conn = self.connection()
424            server_info["__all__"] = {
425                "status": "ok",
426                **self.get_ldap_server_info(conn.server),
427            }
428        except LDAPException as exc:
429            server_info["__all__"] = {
430                "status": str(exc),
431            }
432        return server_info
433
434    class Meta:
435        verbose_name = _("LDAP Source")
436        verbose_name_plural = _("LDAP Sources")
437
438
439class LDAPSourcePropertyMapping(PropertyMapping):
440    """Map LDAP Property to User or Group object attribute"""
441
442    expression_allowed_types = [dict]
443
444    @property
445    def component(self) -> str:
446        return "ak-property-mapping-source-ldap-form"
447
448    @property
449    def serializer(self) -> type[Serializer]:
450        from authentik.sources.ldap.api.property_mappings import LDAPSourcePropertyMappingSerializer
451
452        return LDAPSourcePropertyMappingSerializer
453
454    def __str__(self):
455        return str(self.name)
456
457    class Meta:
458        verbose_name = _("LDAP Source Property Mapping")
459        verbose_name_plural = _("LDAP Source Property Mappings")
460
461
462class UserLDAPSourceConnection(UserSourceConnection):
463    validated_by = models.UUIDField(
464        null=True,
465        blank=True,
466        help_text=_("Unique ID used while checking if this object still exists in the directory."),
467    )
468
469    @property
470    def serializer(self) -> type[Serializer]:
471        from authentik.sources.ldap.api.connections import (
472            UserLDAPSourceConnectionSerializer,
473        )
474
475        return UserLDAPSourceConnectionSerializer
476
477    class Meta:
478        verbose_name = _("User LDAP Source Connection")
479        verbose_name_plural = _("User LDAP Source Connections")
480        indexes = [
481            models.Index(fields=["validated_by"]),
482        ]
483
484
485class GroupLDAPSourceConnection(GroupSourceConnection):
486    validated_by = models.UUIDField(
487        null=True,
488        blank=True,
489        help_text=_("Unique ID used while checking if this object still exists in the directory."),
490    )
491
492    @property
493    def serializer(self) -> type[Serializer]:
494        from authentik.sources.ldap.api.connections import (
495            GroupLDAPSourceConnectionSerializer,
496        )
497
498        return GroupLDAPSourceConnectionSerializer
499
500    class Meta:
501        verbose_name = _("Group LDAP Source Connection")
502        verbose_name_plural = _("Group LDAP Source Connections")
503        indexes = [
504            models.Index(fields=["validated_by"]),
505        ]
LDAP_TIMEOUT = 15
LDAP_UNIQUENESS = 'ldap_uniq'

Deprecated, don't use

LDAP_DISTINGUISHED_NAME = 'distinguishedName'
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
def flatten(value: Any) -> Any:
42def flatten(value: Any) -> Any:
43    """Flatten `value` if its a list, set or tuple"""
44    if isinstance(value, list | set | tuple):
45        if len(value) < 1:
46            return None
47        if isinstance(value, set):
48            return value.pop()
49        return value[0]
50    return value

Flatten value if its a list, set or tuple

class MultiURLValidator(authentik.lib.models.DomainlessURLValidator):
53class MultiURLValidator(DomainlessURLValidator):
54    """Same as DomainlessURLValidator but supports multiple URLs separated with a comma."""
55
56    def __call__(self, value: str):
57        if "," in value:
58            for url in value.split(","):
59                super().__call__(url)
60        else:
61            super().__call__(value)

Same as DomainlessURLValidator but supports multiple URLs separated with a comma.

class LDAPSourceBindMethod(django.db.models.enums.TextChoices):
64class LDAPSourceBindMethod(models.TextChoices):
65    """Authentication method for LDAP service connections."""
66
67    SIMPLE = "simple", _("Simple or anonymous bind")
68    SASL_EXTERNAL = "sasl_external", _("SASL EXTERNAL")

Authentication method for LDAP service connections.

 71class LDAPSource(IncomingSyncSource):
 72    """Federate LDAP Directory with authentik, or create new accounts in LDAP."""
 73
 74    server_uri = models.TextField(
 75        validators=[MultiURLValidator(schemes=["ldap", "ldaps"])],
 76        verbose_name=_("Server URI"),
 77    )
 78    peer_certificate = models.ForeignKey(
 79        CertificateKeyPair,
 80        on_delete=models.SET_DEFAULT,
 81        default=None,
 82        null=True,
 83        related_name="ldap_peer_certificates",
 84        help_text=_(
 85            "Optionally verify the LDAP Server's Certificate against the CA Chain in this keypair."
 86        ),
 87    )
 88    client_certificate = models.ForeignKey(
 89        CertificateKeyPair,
 90        on_delete=models.SET_DEFAULT,
 91        default=None,
 92        null=True,
 93        related_name="ldap_client_certificates",
 94        help_text=_("Client certificate to authenticate against the LDAP Server's Certificate."),
 95    )
 96
 97    bind_cn = models.TextField(verbose_name=_("Bind CN"), blank=True)
 98    bind_password = models.TextField(blank=True)
 99    service_bind_method = models.TextField(
100        choices=LDAPSourceBindMethod,
101        default=LDAPSourceBindMethod.SIMPLE,
102        help_text=_("Authentication method used for LDAP synchronization and writeback."),
103    )
104    start_tls = models.BooleanField(default=False, verbose_name=_("Enable Start TLS"))
105    sni = models.BooleanField(default=False, verbose_name=_("Use Server URI for SNI verification"))
106
107    base_dn = models.TextField(verbose_name=_("Base DN"))
108    additional_user_dn = models.TextField(
109        help_text=_("Prepended to Base DN for User-queries."),
110        verbose_name=_("Addition User DN"),
111        blank=True,
112    )
113    additional_group_dn = models.TextField(
114        help_text=_("Prepended to Base DN for Group-queries."),
115        verbose_name=_("Addition Group DN"),
116        blank=True,
117    )
118
119    user_object_filter = models.TextField(
120        default="(objectClass=person)",
121        help_text=_("Consider Objects matching this filter to be Users."),
122    )
123    user_membership_attribute = models.TextField(
124        default=LDAP_DISTINGUISHED_NAME,
125        help_text=_("Attribute which matches the value of `group_membership_field`."),
126    )
127    group_membership_field = models.TextField(
128        default="member", help_text=_("Field which contains members of a group.")
129    )
130    group_object_filter = models.TextField(
131        default="(objectClass=group)",
132        help_text=_("Consider Objects matching this filter to be Groups."),
133    )
134    object_uniqueness_field = models.TextField(
135        default="objectSid", help_text=_("Field which contains a unique Identifier.")
136    )
137
138    password_login_update_internal_password = models.BooleanField(
139        default=False,
140        help_text=_("Update internal authentik password when login succeeds with LDAP"),
141    )
142
143    sync_users = models.BooleanField(default=True)
144    sync_users_password = models.BooleanField(
145        default=True,
146        help_text=_(
147            "When a user changes their password, sync it back to LDAP. "
148            "This can only be enabled on a single LDAP source."
149        ),
150    )
151    sync_groups = models.BooleanField(default=True)
152    sync_parent_group = models.ForeignKey(
153        Group, blank=True, null=True, default=None, on_delete=models.SET_DEFAULT
154    )
155
156    sync_group_hierarchy = models.BooleanField(
157        default=False, help_text=_("Sync group parentage/hierarchy from LDAP directories.")
158    )
159
160    lookup_groups_from_user = models.BooleanField(
161        default=False,
162        help_text=_(
163            "Lookup group membership based on a user attribute instead of a group attribute. "
164            "This allows nested group resolution on systems like FreeIPA and Active Directory"
165        ),
166    )
167
168    delete_not_found_objects = models.BooleanField(
169        default=False,
170        help_text=_(
171            "Delete authentik users and groups which were previously supplied by this source, "
172            "but are now missing from it."
173        ),
174    )
175
176    @property
177    def component(self) -> str:
178        return "ak-source-ldap-form"
179
180    @property
181    def serializer(self) -> type[Serializer]:
182        from authentik.sources.ldap.api.sources import LDAPSourceSerializer
183
184        return LDAPSourceSerializer
185
186    @property
187    def schedule_specs(self) -> list[ScheduleSpec]:
188        from authentik.sources.ldap.tasks import ldap_connectivity_check, ldap_sync
189
190        return [
191            ScheduleSpec(
192                actor=ldap_sync,
193                uid=self.slug,
194                args=(self.pk,),
195                crontab=f"{fqdn_rand('ldap_sync/' + str(self.pk))} */2 * * *",
196                send_on_save=True,
197            ),
198            ScheduleSpec(
199                actor=ldap_connectivity_check,
200                uid=self.slug,
201                args=(self.pk,),
202                crontab=f"{fqdn_rand('ldap_connectivity_check/' + str(self.pk))} * * * *",
203                send_on_save=True,
204            ),
205        ]
206
207    @property
208    def property_mapping_type(self) -> type[PropertyMapping]:
209        from authentik.sources.ldap.models import LDAPSourcePropertyMapping
210
211        return LDAPSourcePropertyMapping
212
213    def update_properties_with_uniqueness_field(self, properties, dn, ldap, **kwargs):
214        properties.setdefault("attributes", {})[LDAP_DISTINGUISHED_NAME] = dn
215        # TODO: Remove after 2026.5, still stored for legacy
216        if self.object_uniqueness_field in ldap:
217            properties["attributes"][LDAP_UNIQUENESS] = flatten(
218                ldap.get(self.object_uniqueness_field)
219            )
220        return properties
221
222    def get_base_user_properties(self, **kwargs):
223        return self.update_properties_with_uniqueness_field({}, **kwargs)
224
225    def get_base_group_properties(self, **kwargs):
226        return self.update_properties_with_uniqueness_field(
227            {
228                "parent": self.sync_parent_group,
229            },
230            **kwargs,
231        )
232
233    @property
234    def icon_url(self) -> str:
235        return static("authentik/sources/ldap/light.svg")
236
237    def server(self, **kwargs) -> ServerPool:
238        """Get LDAP Server/ServerPool"""
239        # ldap3 is only imported when an LDAP source is used
240        from ldap3 import ALL, RANDOM, Server, ServerPool, Tls
241
242        servers = []
243        tls_kwargs = {}
244        if self.peer_certificate:
245            tls_kwargs["ca_certs_data"] = self.peer_certificate.certificate_data
246            tls_kwargs["validate"] = CERT_REQUIRED
247        if self.client_certificate:
248            temp_dir = mkdtemp()
249            with NamedTemporaryFile(mode="w", delete=False, dir=temp_dir) as temp_cert:
250                temp_cert.write(self.client_certificate.certificate_data)
251                certificate_file = temp_cert.name
252                chmod(certificate_file, 0o600)
253            with NamedTemporaryFile(mode="w", delete=False, dir=temp_dir) as temp_key:
254                temp_key.write(self.client_certificate.key_data)
255                private_key_file = temp_key.name
256                chmod(private_key_file, 0o600)
257            tls_kwargs["local_private_key_file"] = private_key_file
258            tls_kwargs["local_certificate_file"] = certificate_file
259        if ciphers := CONFIG.get("ldap.tls.ciphers", None):
260            tls_kwargs["ciphers"] = ciphers.strip()
261        server_kwargs = {
262            "get_info": ALL,
263            "connect_timeout": LDAP_TIMEOUT,
264        }
265        server_kwargs.update(kwargs)
266        for server_uri in self.server_uri.split(","):
267            server = Server(server_uri.strip(), **server_kwargs)
268            # The TLS SNI server name must be a bare hostname. ldap3 has already
269            # parsed the scheme and port out of the URI into `server.host`;
270            # passing the raw URI (e.g. `ldaps://host`) as the SNI name breaks
271            # the handshake against SNI-strict servers. See #7756.
272            server.tls = Tls(**tls_kwargs, sni=server.host if self.sni else None)
273            servers.append(server)
274        return ServerPool(servers, RANDOM, active=5, exhaust=True)
275
276    def connection(
277        self,
278        server: Server | None = None,
279        server_kwargs: dict | None = None,
280        connection_kwargs: dict | None = None,
281    ) -> Connection:
282        """Get a service connection for synchronization, searches, and writeback."""
283        from ldap3 import EXTERNAL, SASL
284
285        connection_kwargs = dict(connection_kwargs or {})
286        if self.service_bind_method == LDAPSourceBindMethod.SASL_EXTERNAL:
287            self._validate_sasl_external_configuration()
288            connection_kwargs.pop("user", None)
289            connection_kwargs.pop("password", None)
290            connection_kwargs.update(
291                authentication=SASL,
292                sasl_mechanism=EXTERNAL,
293                sasl_credentials="",
294            )
295        else:
296            connection_kwargs.setdefault("user", self.bind_cn)
297            connection_kwargs.setdefault("password", self.bind_password)
298        return self._connect_and_bind(server, server_kwargs, connection_kwargs)
299
300    def connection_as_user(self, user: str, password: str) -> Connection:
301        """Bind as an LDAP user to verify their submitted password."""
302        from ldap3 import SIMPLE
303
304        return self._connect_and_bind(
305            connection_kwargs={
306                "user": user,
307                "password": password,
308                "authentication": SIMPLE,
309            }
310        )
311
312    def _validate_sasl_external_configuration(self) -> None:
313        """Ensure SASL EXTERNAL has a certificate-backed TLS transport."""
314        from ldap3.core.exceptions import LDAPConfigurationError
315
316        if not self.client_certificate or not self.client_certificate.key_data:
317            raise LDAPConfigurationError(
318                "SASL EXTERNAL requires a client certificate with a private key"
319            )
320        schemes = {urlparse(uri.strip()).scheme for uri in self.server_uri.split(",")}
321        expected_schemes = {"ldap"} if self.start_tls else {"ldaps"}
322        if schemes != expected_schemes:
323            raise LDAPConfigurationError(
324                "SASL EXTERNAL requires ldap:// with StartTLS or ldaps:// without StartTLS"
325            )
326
327    def _connect_and_bind(
328        self,
329        server: Server | None = None,
330        server_kwargs: dict | None = None,
331        connection_kwargs: dict | None = None,
332    ) -> Connection:
333        """Create, secure, and bind an LDAP connection."""
334        from ldap3 import ALL, NONE, Connection
335        from ldap3.core.exceptions import (
336            LDAPAdminLimitExceededResult,
337            LDAPAttributeError,
338            LDAPException,
339            LDAPInsufficientAccessRightsResult,
340            LDAPSchemaError,
341        )
342
343        server_kwargs = server_kwargs or {}
344        connection_kwargs = connection_kwargs or {}
345        conn = Connection(
346            server or self.server(**server_kwargs),
347            raise_exceptions=True,
348            receive_timeout=LDAP_TIMEOUT,
349            **connection_kwargs,
350        )
351
352        if self.start_tls:
353            LOGGER.debug("Connection StartTLS", source=self)
354            conn.start_tls(read_server_info=False)
355        try:
356            successful = conn.bind()
357            if successful:
358                return conn
359        except (
360            LDAPSchemaError,
361            LDAPInsufficientAccessRightsResult,
362            LDAPAdminLimitExceededResult,
363            LDAPAttributeError,
364        ) as exc:
365            # Schema error or rate limit during schema fetch, retry without schema info
366            # See https://github.com/goauthentik/authentik/issues/4590
367            # See also https://github.com/goauthentik/authentik/issues/3399
368            # LDAPAdminLimitExceededResult: Google Secure LDAP rate-limits schema queries
369            # LDAPAttributeError: Google Secure LDAP returns unsupported attrs in schema
370            if server_kwargs.get("get_info", ALL) == NONE:
371                LOGGER.warning("Failed to connect after schema downgrade", source=self, exc=exc)
372                raise exc
373            LOGGER.warning("Downgrading connection to no schema info", source=self, exc=exc)
374            server_kwargs["get_info"] = NONE
375            return self._connect_and_bind(server, server_kwargs, connection_kwargs)
376        finally:
377            if conn.server.tls.certificate_file is not None and exists(
378                conn.server.tls.certificate_file
379            ):
380                rmtree(dirname(conn.server.tls.certificate_file))
381        raise LDAPException("Failed to bind")
382
383    @property
384    def sync_lock(self) -> pglock.advisory:
385        """Postgres lock for syncing LDAP to prevent multiple parallel syncs happening"""
386        return pglock.advisory(
387            lock_id=f"goauthentik.io/{connection.schema_name}/sources/ldap/sync/{self.slug}",
388            timeout=0,
389            side_effect=pglock.Return,
390            using=advisory_lock_db_alias(),
391        )
392
393    def get_ldap_server_info(self, srv: Server) -> dict[str, str]:
394        info = {
395            "vendor": _("N/A"),
396            "version": _("N/A"),
397        }
398        if srv.info:
399            info["vendor"] = str(flatten(srv.info.vendor_name))
400            info["version"] = str(flatten(srv.info.vendor_version))
401        return info
402
403    def check_connection(self) -> dict[str, dict[str, str]]:
404        """Check LDAP Connection"""
405        from ldap3.core.exceptions import LDAPException
406
407        servers = self.server()
408        server_info = {}
409        # Check each individual server
410        for server in servers.servers:
411            server: Server
412            try:
413                conn = self.connection(server=server)
414                server_info[server.host] = {
415                    "status": "ok",
416                    **self.get_ldap_server_info(conn.server),
417                }
418            except LDAPException as exc:
419                server_info[server.host] = {
420                    "status": str(exc),
421                }
422        # Check server pool
423        try:
424            conn = self.connection()
425            server_info["__all__"] = {
426                "status": "ok",
427                **self.get_ldap_server_info(conn.server),
428            }
429        except LDAPException as exc:
430            server_info["__all__"] = {
431                "status": str(exc),
432            }
433        return server_info
434
435    class Meta:
436        verbose_name = _("LDAP Source")
437        verbose_name_plural = _("LDAP Sources")

Federate LDAP Directory with authentik, or create new accounts in LDAP.

def server_uri(unknown):

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

peer_certificate

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.

client_certificate

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

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

def bind_password(unknown):

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

def service_bind_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 start_tls(unknown):

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

def sni(unknown):

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

def base_dn(unknown):

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

def additional_user_dn(unknown):

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

def additional_group_dn(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_object_filter(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_membership_attribute(unknown):

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

def group_membership_field(unknown):

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

def group_object_filter(unknown):

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

def object_uniqueness_field(unknown):

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

def password_login_update_internal_password(unknown):

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

def sync_users(unknown):

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

def sync_users_password(unknown):

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

def sync_groups(unknown):

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

sync_parent_group

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

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

def lookup_groups_from_user(unknown):

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

def delete_not_found_objects(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
176    @property
177    def component(self) -> str:
178        return "ak-source-ldap-form"

Return component used to edit this object

serializer: type[rest_framework.serializers.Serializer]
180    @property
181    def serializer(self) -> type[Serializer]:
182        from authentik.sources.ldap.api.sources import LDAPSourceSerializer
183
184        return LDAPSourceSerializer

Get serializer for this model

schedule_specs: list[authentik.tasks.schedules.common.ScheduleSpec]
186    @property
187    def schedule_specs(self) -> list[ScheduleSpec]:
188        from authentik.sources.ldap.tasks import ldap_connectivity_check, ldap_sync
189
190        return [
191            ScheduleSpec(
192                actor=ldap_sync,
193                uid=self.slug,
194                args=(self.pk,),
195                crontab=f"{fqdn_rand('ldap_sync/' + str(self.pk))} */2 * * *",
196                send_on_save=True,
197            ),
198            ScheduleSpec(
199                actor=ldap_connectivity_check,
200                uid=self.slug,
201                args=(self.pk,),
202                crontab=f"{fqdn_rand('ldap_connectivity_check/' + str(self.pk))} * * * *",
203                send_on_save=True,
204            ),
205        ]
property_mapping_type: type[authentik.core.models.PropertyMapping]
207    @property
208    def property_mapping_type(self) -> type[PropertyMapping]:
209        from authentik.sources.ldap.models import LDAPSourcePropertyMapping
210
211        return LDAPSourcePropertyMapping

Return property mapping type used by this object

def update_properties_with_uniqueness_field(self, properties, dn, ldap, **kwargs):
213    def update_properties_with_uniqueness_field(self, properties, dn, ldap, **kwargs):
214        properties.setdefault("attributes", {})[LDAP_DISTINGUISHED_NAME] = dn
215        # TODO: Remove after 2026.5, still stored for legacy
216        if self.object_uniqueness_field in ldap:
217            properties["attributes"][LDAP_UNIQUENESS] = flatten(
218                ldap.get(self.object_uniqueness_field)
219            )
220        return properties
def get_base_user_properties(self, **kwargs):
222    def get_base_user_properties(self, **kwargs):
223        return self.update_properties_with_uniqueness_field({}, **kwargs)

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

def get_base_group_properties(self, **kwargs):
225    def get_base_group_properties(self, **kwargs):
226        return self.update_properties_with_uniqueness_field(
227            {
228                "parent": self.sync_parent_group,
229            },
230            **kwargs,
231        )

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

icon_url: str
233    @property
234    def icon_url(self) -> str:
235        return static("authentik/sources/ldap/light.svg")

Get the URL to the source icon

def server(unknown):
237    def server(self, **kwargs) -> ServerPool:
238        """Get LDAP Server/ServerPool"""
239        # ldap3 is only imported when an LDAP source is used
240        from ldap3 import ALL, RANDOM, Server, ServerPool, Tls
241
242        servers = []
243        tls_kwargs = {}
244        if self.peer_certificate:
245            tls_kwargs["ca_certs_data"] = self.peer_certificate.certificate_data
246            tls_kwargs["validate"] = CERT_REQUIRED
247        if self.client_certificate:
248            temp_dir = mkdtemp()
249            with NamedTemporaryFile(mode="w", delete=False, dir=temp_dir) as temp_cert:
250                temp_cert.write(self.client_certificate.certificate_data)
251                certificate_file = temp_cert.name
252                chmod(certificate_file, 0o600)
253            with NamedTemporaryFile(mode="w", delete=False, dir=temp_dir) as temp_key:
254                temp_key.write(self.client_certificate.key_data)
255                private_key_file = temp_key.name
256                chmod(private_key_file, 0o600)
257            tls_kwargs["local_private_key_file"] = private_key_file
258            tls_kwargs["local_certificate_file"] = certificate_file
259        if ciphers := CONFIG.get("ldap.tls.ciphers", None):
260            tls_kwargs["ciphers"] = ciphers.strip()
261        server_kwargs = {
262            "get_info": ALL,
263            "connect_timeout": LDAP_TIMEOUT,
264        }
265        server_kwargs.update(kwargs)
266        for server_uri in self.server_uri.split(","):
267            server = Server(server_uri.strip(), **server_kwargs)
268            # The TLS SNI server name must be a bare hostname. ldap3 has already
269            # parsed the scheme and port out of the URI into `server.host`;
270            # passing the raw URI (e.g. `ldaps://host`) as the SNI name breaks
271            # the handshake against SNI-strict servers. See #7756.
272            server.tls = Tls(**tls_kwargs, sni=server.host if self.sni else None)
273            servers.append(server)
274        return ServerPool(servers, RANDOM, active=5, exhaust=True)

Get LDAP Server/ServerPool

def connection(unknown):
276    def connection(
277        self,
278        server: Server | None = None,
279        server_kwargs: dict | None = None,
280        connection_kwargs: dict | None = None,
281    ) -> Connection:
282        """Get a service connection for synchronization, searches, and writeback."""
283        from ldap3 import EXTERNAL, SASL
284
285        connection_kwargs = dict(connection_kwargs or {})
286        if self.service_bind_method == LDAPSourceBindMethod.SASL_EXTERNAL:
287            self._validate_sasl_external_configuration()
288            connection_kwargs.pop("user", None)
289            connection_kwargs.pop("password", None)
290            connection_kwargs.update(
291                authentication=SASL,
292                sasl_mechanism=EXTERNAL,
293                sasl_credentials="",
294            )
295        else:
296            connection_kwargs.setdefault("user", self.bind_cn)
297            connection_kwargs.setdefault("password", self.bind_password)
298        return self._connect_and_bind(server, server_kwargs, connection_kwargs)

Get a service connection for synchronization, searches, and writeback.

def connection_as_user(unknown):
300    def connection_as_user(self, user: str, password: str) -> Connection:
301        """Bind as an LDAP user to verify their submitted password."""
302        from ldap3 import SIMPLE
303
304        return self._connect_and_bind(
305            connection_kwargs={
306                "user": user,
307                "password": password,
308                "authentication": SIMPLE,
309            }
310        )

Bind as an LDAP user to verify their submitted password.

sync_lock: pglock.core.advisory
383    @property
384    def sync_lock(self) -> pglock.advisory:
385        """Postgres lock for syncing LDAP to prevent multiple parallel syncs happening"""
386        return pglock.advisory(
387            lock_id=f"goauthentik.io/{connection.schema_name}/sources/ldap/sync/{self.slug}",
388            timeout=0,
389            side_effect=pglock.Return,
390            using=advisory_lock_db_alias(),
391        )

Postgres lock for syncing LDAP to prevent multiple parallel syncs happening

def get_ldap_server_info(unknown):
393    def get_ldap_server_info(self, srv: Server) -> dict[str, str]:
394        info = {
395            "vendor": _("N/A"),
396            "version": _("N/A"),
397        }
398        if srv.info:
399            info["vendor"] = str(flatten(srv.info.vendor_name))
400            info["version"] = str(flatten(srv.info.vendor_version))
401        return info
def check_connection(self) -> dict[str, dict[str, str]]:
403    def check_connection(self) -> dict[str, dict[str, str]]:
404        """Check LDAP Connection"""
405        from ldap3.core.exceptions import LDAPException
406
407        servers = self.server()
408        server_info = {}
409        # Check each individual server
410        for server in servers.servers:
411            server: Server
412            try:
413                conn = self.connection(server=server)
414                server_info[server.host] = {
415                    "status": "ok",
416                    **self.get_ldap_server_info(conn.server),
417                }
418            except LDAPException as exc:
419                server_info[server.host] = {
420                    "status": str(exc),
421                }
422        # Check server pool
423        try:
424            conn = self.connection()
425            server_info["__all__"] = {
426                "status": "ok",
427                **self.get_ldap_server_info(conn.server),
428            }
429        except LDAPException as exc:
430            server_info["__all__"] = {
431                "status": str(exc),
432            }
433        return server_info

Check LDAP Connection

def sync_outgoing_trigger_mode(unknown):

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

schedules

Accessor to the related objects manager on the one-to-many relation created by GenericRelation.

In the example::

class Post(Model):
    comments = GenericRelation(Comment)

post.comments is a ReverseGenericManyToOneDescriptor instance.

tasks

Accessor to the related objects manager on the one-to-many relation created by GenericRelation.

In the example::

class Post(Model):
    comments = GenericRelation(Comment)

post.comments is a ReverseGenericManyToOneDescriptor instance.

peer_certificate_id
client_certificate_id
def get_service_bind_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.

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

def get_sync_outgoing_trigger_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.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class LDAPSourcePropertyMapping(authentik.core.models.PropertyMapping):
440class LDAPSourcePropertyMapping(PropertyMapping):
441    """Map LDAP Property to User or Group object attribute"""
442
443    expression_allowed_types = [dict]
444
445    @property
446    def component(self) -> str:
447        return "ak-property-mapping-source-ldap-form"
448
449    @property
450    def serializer(self) -> type[Serializer]:
451        from authentik.sources.ldap.api.property_mappings import LDAPSourcePropertyMappingSerializer
452
453        return LDAPSourcePropertyMappingSerializer
454
455    def __str__(self):
456        return str(self.name)
457
458    class Meta:
459        verbose_name = _("LDAP Source Property Mapping")
460        verbose_name_plural = _("LDAP Source Property Mappings")

Map LDAP Property to User or Group object attribute

expression_allowed_types = [<class 'dict'>]
component: str
445    @property
446    def component(self) -> str:
447        return "ak-property-mapping-source-ldap-form"

Return component used to edit this object

serializer: type[rest_framework.serializers.Serializer]
449    @property
450    def serializer(self) -> type[Serializer]:
451        from authentik.sources.ldap.api.property_mappings import LDAPSourcePropertyMappingSerializer
452
453        return LDAPSourcePropertyMappingSerializer

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 LDAPSourcePropertyMapping.DoesNotExist(authentik.core.models.PropertyMapping.DoesNotExist):

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class UserLDAPSourceConnection(authentik.core.models.UserSourceConnection):
463class UserLDAPSourceConnection(UserSourceConnection):
464    validated_by = models.UUIDField(
465        null=True,
466        blank=True,
467        help_text=_("Unique ID used while checking if this object still exists in the directory."),
468    )
469
470    @property
471    def serializer(self) -> type[Serializer]:
472        from authentik.sources.ldap.api.connections import (
473            UserLDAPSourceConnectionSerializer,
474        )
475
476        return UserLDAPSourceConnectionSerializer
477
478    class Meta:
479        verbose_name = _("User LDAP Source Connection")
480        verbose_name_plural = _("User LDAP Source Connections")
481        indexes = [
482            models.Index(fields=["validated_by"]),
483        ]

UserLDAPSourceConnection(id, created, last_updated, user, source, identifier, usersourceconnection_ptr, validated_by)

def validated_by(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]
470    @property
471    def serializer(self) -> type[Serializer]:
472        from authentik.sources.ldap.api.connections import (
473            UserLDAPSourceConnectionSerializer,
474        )
475
476        return UserLDAPSourceConnectionSerializer

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 UserLDAPSourceConnection.DoesNotExist(authentik.core.models.UserSourceConnection.DoesNotExist):

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class GroupLDAPSourceConnection(authentik.core.models.GroupSourceConnection):
486class GroupLDAPSourceConnection(GroupSourceConnection):
487    validated_by = models.UUIDField(
488        null=True,
489        blank=True,
490        help_text=_("Unique ID used while checking if this object still exists in the directory."),
491    )
492
493    @property
494    def serializer(self) -> type[Serializer]:
495        from authentik.sources.ldap.api.connections import (
496            GroupLDAPSourceConnectionSerializer,
497        )
498
499        return GroupLDAPSourceConnectionSerializer
500
501    class Meta:
502        verbose_name = _("Group LDAP Source Connection")
503        verbose_name_plural = _("Group LDAP Source Connections")
504        indexes = [
505            models.Index(fields=["validated_by"]),
506        ]

GroupLDAPSourceConnection(id, created, last_updated, group, source, identifier, groupsourceconnection_ptr, validated_by)

def validated_by(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]
493    @property
494    def serializer(self) -> type[Serializer]:
495        from authentik.sources.ldap.api.connections import (
496            GroupLDAPSourceConnectionSerializer,
497        )
498
499        return GroupLDAPSourceConnectionSerializer

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 GroupLDAPSourceConnection.DoesNotExist(authentik.core.models.GroupSourceConnection.DoesNotExist):

The requested object does not exist

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

The query returned multiple objects when only one was expected.