django通过LDAP进行用户身份验证

时间:2019-10-25 10:01:46

标签: python django active-directory ldap

我正在尝试通过ldap根据我们的广告检查django项目中的用户登录。 到目前为止,我已经在网上找到了很多教程。

由于某种原因,authenticate(username, password)函数返回None

到目前为止,这是我的代码:

views.py(登录)

def login_view(request):
    if not request.user.is_authenticated:
        if request.method == 'POST':
            login_form = Login_form(request.POST)
            if login_form.is_valid():
                username = login_form.data.get('username')
                password = login_form.data.get('password')
                domain_name = "@my.domain.com"
                if domain_name not in username:
                    username += domain_name
                try:
                    user = authenticate(username=username, password=password)
                    print(user) # this gives me None
                    if user is not None:
                        if user.is_active:
                            login(request=request, user=user)
                            return redirect('index')
                    else:
                        form = AuthenticationForm()
                        messages.error(request, 'Try again!')
                        return render(request, 'myapp/login.html', {'form': form})
                except ldap.LDAPError as e:
                    print(e) # no error is displayed here
                    form = AuthenticationForm()
                    messages.error(request, 'Try again!')
                    return render(request, 'myapp/login.html', {'form': form})
          ### Some more funcs to  
          ### redirect to login.html
          ### if the login fails

settings.py:

AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
)

AUTH_LDAP_SERVER_URI = "ldap://my.domain.com:389"
AUTH_LDAP_BIND_DN = "CN=Users,DC=my,DC=domain,DC=com"
AUTH_LDAP_BIND_PASSWORD = ""    # I tried with blank password for anonymous bind or
                                # with "%(password)s" as template but I don't know if that's possible
                                # and also without the AUTH_LDAP_BIND_PASSWORD setting
AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS: 0}
AUTH_LDAP_USER_ATTR_MAP = {'group': "memberof", "first_name": "givenName", "last_name": "sn"}
AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=my,DC=domain,DC=com,CN=Users",
                                   ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") 
# since we need to login via username i need to search for username@my.domain.com 
# so I try to search for sAMAccountName

前段时间,我用PHP编写了LDAP登录脚本,其工作方式类似于超级按钮,所有DN,绑定和搜索都相同。

所以我的问题是:

哪里出错了,或者我想念什么?

1 个答案:

答案 0 :(得分:0)

我强烈建议您使用django-python3-ldap。在尝试了其他软件包之后,我们已经在生产中使用了此软件包多年,它可以正常工作,并且完全用Python 3编写:https://github.com/etianen/django-python3-ldap

我们在端口636和ldaps上使用它,它也可以正常工作。

它使我们不必编写自己的自定义后端或登录方法;我们要做的就是更改一些设置并编写format_username函数。自述文件提供了有关挂接到Active Directory的良好信息:我将从该配置开始,然后看它如何工作。祝你好运!