简体   繁体   English

无法使用Django和ldap进行身份验证

[英]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. 我使用一个简单的表单,它采用用户名和密码,并尝试使用ldap服务器来验证该用户。 The actual portal of the dashboard is written in php, but I have to rewrite it using django (and pyldap). 仪表板的实际门户是用PHP编写的,但我必须使用django(和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). 在我的settings.py文件中,我进行了以下设置(我修改了URI,因为我正在工作的公司使用它)。

# 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) 在我的views.py中,我有以下代码(仅用于测试)

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/". login.html包含一个带有表单的简单HTML代码,其中method =“post”action =“/ login /”。 Index.html contains a simple "success" message, and error.html contains a simple "wrong!" Index.html包含一个简单的“成功”消息,而error.html包含一个简单的“错误!” 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. 而不是上面代码中使用的authenticate方法。 Unfortunately, I'm getting the same behavior. 不幸的是,我得到了同样的行为。 What am I missing, where is my mistake? 我错过了什么,我的错误在哪里?

Finnaly, I manage to do it. Finnaly,我设法做到了。 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! 祝你有美好的一天!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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