Repository: netbox-community/netbox

Issue:
Move LDAP authentication into a standalone authentication backend
### Proposed Changes
With the introduction of support for custom authentication backends (#2328) in NetBox v2.8, it no longer makes sense to maintain LDAP authentication as part of NetBox's core.

### Justification
Offloading this functionality removes the burden of maintenance from the core maintainers, encourages more community participation in the development of the LDAP backend itself, and should serve as a strong reference implementation for custom authentication backends. It will also help guide the development of remote authentication support in NetBox.


Discussion:
I'll repeat here that it would be nice if the LDAP module could also be used as an authorization module when external authentication is used. I don't know how doable/complex that would be.

After authentication is completed externally the user's group memberships are read from LDAP for permissions.
@bluikko That is beyond the scope of this issue.
Since its possible to using an LDAP backend as custom authentication backend thats seems like a good idea. 
A Problem could be if someone wants to use both ldap and another custom authentication backend. A possible solution would be to allow the use of more than one custom backend.

Resolving patch:
diff --git a/netbox/netbox/authentication.py b/netbox/netbox/authentication.py
--- a/netbox/netbox/authentication.py
+++ b/netbox/netbox/authentication.py
@@ -3,6 +3,7 @@
 from django.conf import settings
 from django.contrib.auth.backends import ModelBackend, RemoteUserBackend as _RemoteUserBackend
 from django.contrib.auth.models import Group
+from django.core.exceptions import ImproperlyConfigured
 from django.db.models import Q
 
 from users.models import ObjectPermission
@@ -132,3 +133,50 @@ def configure_user(self, request, user):
 
     def has_perm(self, user_obj, perm, obj=None):
         return False
+
+
+class LDAPBackend:
+
+    def __new__(cls, *args, **kwargs):
+        try:
+            import ldap
+            from django_auth_ldap.backend import LDAPBackend as LDAPBackend_, LDAPSettings
+        except ImportError:
+            raise ImproperlyConfigured(
+                "LDAP authentication has been configured, but django-auth-ldap is not installed."
+            )
+
+        try:
+            from netbox import ldap_config
+        except ImportError:
+            raise ImproperlyConfigured(
+                "ldap_config.py does not exist"
+            )
+
+        try:
+            getattr(ldap_config, 'AUTH_LDAP_SERVER_URI')
+        except AttributeError:
+            raise ImproperlyConfigured(
+                "Required parameter AUTH_LDAP_SERVER_URI is missing from ldap_config.py."
+            )
+
+        # Create a new instance of django-auth-ldap's LDAPBackend
+        obj = LDAPBackend_()
+
+        # Read LDAP configuration parameters from ldap_config.py instead of settings.py
+        settings = LDAPSettings()
+        for param in dir(ldap_config):
+            if param.startswith(settings._prefix):
+                setattr(settings, param[10:], getattr(ldap_config, param))
+        obj.settings = settings
+
+        # Optionally disable strict certificate checking
+        if getattr(ldap_config, 'LDAP_IGNORE_CERT_ERRORS', False):
+            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
+
+        # Enable logging for django_auth_ldap
+        ldap_logger = logging.getLogger('django_auth_ldap')
+        ldap_logger.addHandler(logging.StreamHandler())
+        ldap_logger.setLevel(logging.DEBUG)
+
+        return obj
diff --git a/netbox/netbox/settings.py b/netbox/netbox/settings.py
--- a/netbox/netbox/settings.py
+++ b/netbox/netbox/settings.py
@@ -378,75 +378,6 @@ def _setting(name, default=None):
 
 CSRF_TRUSTED_ORIGINS = ALLOWED_HOSTS
 
-
-#
-# LDAP authentication (optional)
-#
-
-try:
-    from netbox import ldap_config as LDAP_CONFIG
-except ImportError:
-    LDAP_CONFIG = None
-
-if LDAP_CONFIG is not None:
-
-    # Check that django_auth_ldap is installed
-    try:
-        import ldap
-        import django_auth_ldap
-    except ImportError:
-        raise ImproperlyConfigured(
-            "LDAP authentication has been configured, but django-auth-ldap is not installed. Remove "
-            "netbox/ldap_config.py to disable LDAP."
-        )
-
-    # Required configuration parameters
-    try:
-        AUTH_LDAP_SERVER_URI = getattr(LDAP_CONFIG, 'AUTH_LDAP_SERVER_URI')
-    except AttributeError:
-        raise ImproperlyConfigured(
-            "Required parameter AUTH_LDAP_SERVER_URI is missing from ldap_config.py."
-        )
-
-    # Optional configuration parameters
-    AUTH_LDAP_ALWAYS_UPDATE_USER = getattr(LDAP_CONFIG, 'AUTH_LDAP_ALWAYS_UPDATE_USER', True)
-    AUTH_LDAP_AUTHORIZE_ALL_USERS = getattr(LDAP_CONFIG, 'AUTH_LDAP_AUTHORIZE_ALL_USERS', False)
-    AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = getattr(LDAP_CONFIG, 'AUTH_LDAP_BIND_AS_AUTHENTICATING_USER', False)
-    AUTH_LDAP_BIND_DN = getattr(LDAP_CONFIG, 'AUTH_LDAP_BIND_DN', '')
-    AUTH_LDAP_BIND_PASSWORD = getattr(LDAP_CONFIG, 'AUTH_LDAP_BIND_PASSWORD', '')
-    AUTH_LDAP_CACHE_TIMEOUT = getattr(LDAP_CONFIG, 'AUTH_LDAP_CACHE_TIMEOUT', 0)
-    AUTH_LDAP_CONNECTION_OPTIONS = getattr(LDAP_CONFIG, 'AUTH_LDAP_CONNECTION_OPTIONS', {})
-    AUTH_LDAP_DENY_GROUP = getattr(LDAP_CONFIG, 'AUTH_LDAP_DENY_GROUP', None)
-    AUTH_LDAP_FIND_GROUP_PERMS = getattr(LDAP_CONFIG, 'AUTH_LDAP_FIND_GROUP_PERMS', False)
-    AUTH_LDAP_GLOBAL_OPTIONS = getattr(LDAP_CONFIG, 'AUTH_LDAP_GLOBAL_OPTIONS', {})
-    AUTH_LDAP_GROUP_SEARCH = getattr(LDAP_CONFIG, 'AUTH_LDAP_GROUP_SEARCH', None)
-    AUTH_LDAP_GROUP_TYPE = getattr(LDAP_CONFIG, 'AUTH_LDAP_GROUP_TYPE', None)
-    AUTH_LDAP_MIRROR_GROUPS = getattr(LDAP_CONFIG, 'AUTH_LDAP_MIRROR_GROUPS', None)
-    AUTH_LDAP_MIRROR_GROUPS_EXCEPT = getattr(LDAP_CONFIG, 'AUTH_LDAP_MIRROR_GROUPS_EXCEPT', None)
-    AUTH_LDAP_PERMIT_EMPTY_PASSWORD = getattr(LDAP_CONFIG, 'AUTH_LDAP_PERMIT_EMPTY_PASSWORD', False)
-    AUTH_LDAP_REQUIRE_GROUP = getattr(LDAP_CONFIG, 'AUTH_LDAP_REQUIRE_GROUP', None)
-    AUTH_LDAP_NO_NEW_USERS = getattr(LDAP_CONFIG, 'AUTH_LDAP_NO_NEW_USERS', False)
-    AUTH_LDAP_START_TLS = getattr(LDAP_CONFIG, 'AUTH_LDAP_START_TLS', False)
-    AUTH_LDAP_USER_QUERY_FIELD = getattr(LDAP_CONFIG, 'AUTH_LDAP_USER_QUERY_FIELD', None)
-    AUTH_LDAP_USER_ATTRLIST = getattr(LDAP_CONFIG, 'AUTH_LDAP_USER_ATTRLIST', None)
-    AUTH_LDAP_USER_ATTR_MAP = getattr(LDAP_CONFIG, 'AUTH_LDAP_USER_ATTR_MAP', {})
-    AUTH_LDAP_USER_DN_TEMPLATE = getattr(LDAP_CONFIG, 'AUTH_LDAP_USER_DN_TEMPLATE', None)
-    AUTH_LDAP_USER_FLAGS_BY_GROUP = getattr(LDAP_CONFIG, 'AUTH_LDAP_USER_FLAGS_BY_GROUP', {})
-    AUTH_LDAP_USER_SEARCH = getattr(LDAP_CONFIG, 'AUTH_LDAP_USER_SEARCH', None)
-
-    # Optionally disable strict certificate checking
-    if getattr(LDAP_CONFIG, 'LDAP_IGNORE_CERT_ERRORS', False):
-        ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
-
-    # Prepend LDAPBackend to the authentication backends list
-    AUTHENTICATION_BACKENDS.insert(0, 'django_auth_ldap.backend.LDAPBackend')
-
-    # Enable logging for django_auth_ldap
-    ldap_logger = logging.getLogger('django_auth_ldap')
-    ldap_logger.addHandler(logging.StreamHandler())
-    ldap_logger.setLevel(logging.DEBUG)
-
-
 #
 # Caching
 #


Test patch: