Django Authentication Ldap Full example
Asked Answered
B

2

8

I partially understood the Django Ldap Authentication. Can anyone give the full example developing very basic application that uses Django Authentication Ldap .

I went through this resource and tried to understand many things but still I am not able to understand that how to use it in implementation. How to create user model that will be used along with LdapBackend class, and how to write many stuff within authenticate() method etc.

Breana answered 6/2, 2019 at 9:4 Comment(0)
G
7

Here you can see a full example very well guided showing how to create a custom LDAPBackend.

You need to configure your LDAP settings in settings.py (as shown in the link you posted) and add your LDAPBackend to AUTHENTICATION_BACKENDS. You can use the default LDAPBackend provided or create a custom one and use that.

Using the default LDAPBackend provided by django-auth-ldap:

AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)

Using a custom LDAPBackend if you need to add extra logic to the authentication:

AUTHENTICATION_BACKENDS = (
    'accounts.backends.MyLDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)

Then in accounts/backends.py:

from django_auth_ldap.backend import LDAPBackend

class MyLDAPBackend(LDAPBackend):
    """ A custom LDAP authentication backend """

    def authenticate(self, username, password):
        """ Overrides LDAPBackend.authenticate to add custom logic """

        user = LDAPBackend().authenticate(self, username, password)

        """ Add custom logic here """

        return user

Check the example linked above for more details.

If you are new to LDAP I would recommend to take a look at this answer (and the other one as well) in another question regarding this topic.


UPDATE FOR NEWER VERSIONS OF django-auth-ldap

Thanks @wolf2600 for pointing out that now instead of authenticate you'll need to override authenticate_ldap_user instead.

Ganley answered 6/2, 2019 at 14:22 Comment(0)
C
4

Of note: The syntax for django_auth_ldap has changed. Intead of overriding authenticate you'll need to override authenticate_ldap_user

https://django-auth-ldap.readthedocs.io/en/latest/custombehavior.html

    def authenticate_ldap_user(self, username, password):
        """ Overrides LDAPBackend.authenticate to save user password in django """
        user = LDAPBackend.authenticate_ldap_user(self, username, password)

        # If user has successfully logged in, save password in django database
        if user:
            user.set_password(password)
            user.save()

        return user

I was kicking myself for hours (coughdayscough) wondering why my custom authenticate wasn't being called until I found that readthedocs.io page.

Caine answered 17/2, 2022 at 23:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.