简体   繁体   中英

Can not authenticate using Django and ldap

I am using a simple form which takes an username and a password and tries to use a ldap server to authenticate that user. The actual portal of the dashboard is written in php, but I have to rewrite it using django (and pyldap). In my settings.py file, I have the following set up (I modified the URI since is used by the company where I am working at).

# LDAP Settings
# Set backends
AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
)

# LDAP Server
AUTH_LDAP_SERVER_URI = 'ldaps://eddie.xy.zzzzz.com:3268'
AUTH_LDAP_START_TLS = True

# Search settings
AUTH_LDAP_BIND_DN = ""
AUTH_LDAP_BIND_PASSWORD = ""
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=xy,dc=zzzzz,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)")

In my views.py, I have the following code (just to test things)

from django.shortcuts import render
from django.contrib.auth import authenticate
from django_auth_ldap.backend import LDAPBackend # Greyed out

def login(request):
    if request.method == 'POST':
        # Get info from POST request
        usr = request.POST['username']
        pas = request.POST['password']

        # Authenticate the user using provided data
        user = authenticate(username=usr, password=pas)
        print(str(user))

        if user is not None:
            return render(request, 'dashboard/index.html', {})
        else:
            print("The username and password were incorrect.")
            return render(request, 'dashboard/error.html', {})

    elif request.method == 'GET':
        return render(request, 'dashboard/login.html', {})

login.html contains a simple HTML code with a form in it, with method="post" action="/login/". Index.html contains a simple "success" message, and error.html contains a simple "wrong!" message. I am using my (working) credentials in the form I made, but I can't get a success message.

What I also tried, was this:

at = LDAPBackend()
user = authenticate(username=usr, password=pas)

instead of the authenticate method used in the code above. Unfortunately, I'm getting the same behavior. What am I missing, where is my mistake?

Finnaly, I manage to do it. I had to set this variable:

AUTH_LDAP_USER_DN_TEMPLATE = "%(user)s"

and now it's working perfectly. I hope this will maybe help the others. Thanks anyway!

Have a good day!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM