1

I am trying to configure LDAP authentication on my django project.

Before get into django, I have tested following shell command can return successfully.

ldapsearch -H ldap://172.16.34.4 -b "dc=corp,dc=rate,dc=com" -D corp\\peter -W sAMAccountName=peter

result:

...
# search result
search: 2
result: 0 Success

# numResponses: 3
# numEntries: 1
# numReferences: 1

But when comes to django settings.py, You know there are many items to set. And I tried many combinations but with no lucky.

AUTH_LDAP_SERVER_URI = 'ldap://172.16.34.4'
AUTH_LDAP_USER_SEARCH = LDAPSearch(
    "DC=corp,dc=rate,dc=com",
    ldap.SCOPE_SUBTREE,
    "(sAMAccountName=%(user)s)"
)
AUTH_LDAP_USER_ATTR_MAP = {
    "username": "sAMAccountName",
    "name": "cn",
    "email": "mail",
    "first_name": "displayName",
    "last_name": "sn"
}
AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend'
)

And I create a API to login:

from rest_framework.views import APIView

class LoginAuth(APIView):
    def post(self, request, *args, **kwargs):
        user_loggedin = 'guest'
        display_name = 'guest'
        username = self.request.data.get('username')
        password = self.request.data.get('password')
        usergo = authenticate(username=username, password=password)  # usergo always returns None
        print('authuser', usergo)
        if usergo is not None:
            auth_login(self.request, usergo)
            user_loggedin = usergo.username
            display_name = usergo.first_name
            context = {
                'username': user_loggedin,
                'displayName': display_name,
                'state': False
            }
            return Response(context, status=status.HTTP_200_OK)
        return Response(
            f'Failed to authenticate with {username} / {password}',
            status=status.HTTP_400_BAD_REQUEST
        )

When access the endpoint with post data, I got error as the following (usergo always returns None):

post data:

{
    "username": "corp\\peter",
    "password": "mypassword"
}

Authentication failed for peter: failed to map the username to a DN.

Could anyone can help me out? I guess there should be some errors in the settings.py configuration.

TangHongWan
  • 645
  • 1
  • 6
  • 18
  • Try to use ldap logs, integrate ldap logger with django. It will useful for future cases as well https://django-auth-ldap.readthedocs.io/en/latest/logging.html Do confirm the dn, using phpldapadmin (install if you don't have it) Try to perform a direct simple bind, and see if that works Note: I prefer docker implementation, it easier to use. – Nishan Paudel Jun 07 '21 at 12:14

0 Answers0