登录页面上的 Django-LDAP 身份验证

时间:2021-05-26 07:28:02

标签: python python-3.x django django-views ldap

我的任务是在 Django 应用程序上实现 LDAP 用户身份验证。

我对 Django 很陌生,因此在寻找这个问题的解决方案时遇到了很多问题,因为 Stackoverflow 上的所有可用资源或答案要么太旧,要么没有我正在使用的类似方法。

我已经在我的 views.py 和 settings.py 中进行了更改,安装了 ldap 正常运行所需的所有包。

但是我不知道如何将 ldap 与我制作的登录表单相关联。

我将分享我为 LDAP 工作所做的所有更改。

如果您能解决我的问题,我将不胜感激。

这是我的:

settings.py

import ldap
AUTH_LDAP_SERVER_URI = "ldap://myldapserver.com"
AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS : 0}
AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s, OU=USERS,dc=myldapserver, dc=com"
AUTH_LDAP_START_TLS = True

AUTHENTICATION_BACKENDS = ["django_auth_ldap.backend.LDAPBackend"]

views.py

from django.contrib.auth import authenticate, login 
import ldap

    def ldap_auth(username, password):
        conn = ldap.initialize(myproj.settings.LDAP_AUTH_URI)
        try:
            ldap.set_option(ldap.OPT_REFERRALS, 0)
            #ldap.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
            conn.simple_bind_s(username, password)
        except ldap.LDAPError as e:
            return f'failed to authenticate'
    
        conn.unbind_s()
        #return "Success" 
        return render(request, 'login.html') #not sure if I need to use the above commented line, as it is not linked to any page so it will fail. 

urls.py

path("login/", views.ldap_auth, name='login'),

登录.html

<div class="container">
    <form method="POST" action="{% url 'login' %}">
        {% csrf_token %}
 <div class="form-group">
    <label for="username">Username</label>
    <input type="username" class="form-control" id="username" placeholder="Enter username">

  </div>
  <div class="form-group">
    <label for="pass">Password</label>
    <input type="password" class="form-control" id="pass" placeholder="Password">
  </div>

  <button type="submit" class="btn btn-primary">Submit</button>
</form>

</div>

请让我知道我还需要在 settings.py、login.html、views.py 中添加什么。

在当前情况下运行后,出现以下错误:

enter image description here

我从答案中得到了帮助:

  1. How to implement ldap authentication(without admin credentials) in django

非常感谢您阅读到这里。如果您需要更多信息。我会帮助您提供这一点,因为这对我来说非常重要,因为我已经过去了几天但仍然没有得到解决方案。

0 个答案:

没有答案