简体   繁体   English

了解 Django-LDAP 身份验证

[英]Understanding Django-LDAP authentication

I am new to Django and have been assigned the task of implementing a user authentication system with LDAP as the backend.我是 Django 的新手,并被分配了一个任务,即以 LDAP 作为后端实现用户身份验证系统。 I guess the documentation assumes that the end developer has enough experience in Django to be able to understand and implement such a system.我猜文档假设最终开发人员在 Django 中有足够的经验能够理解和实现这样的系统。 This is where I fail to understand how to implement a simple django application with LDAP based authentication.这是我无法理解如何使用基于 LDAP 的身份验证实现简单的 django 应用程序的地方。 Here is what I have understood so far:这是我到目前为止所了解的:

Only posting the changes to a file:仅将更改发布到文件:

settings.py
....
import ldap
from django_auth_ldap.config import LDAPSearch

AUTH_LDAP_SERVER_URI = "ldap://<my url>" 
AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend')

AUTH_LDAP_CONNECTION_OPTIONS = { 
    ldap.OPT_REFERRALS: 0
}

MIDDLEWARE_CLASSES = ( 
     ....
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...
)

INSTALLED_APPS = ( 
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    ....
)

auth.html auth.html

<html>
    <head>
        <title>Login</title>
    </head>
    <body>
        {{state}}
        <form action="" method="post"> {% csrf_token %}
            Email address: <input type="text" name="email" value="{{ email }}" />
            Password: <input type="password" name="password" value="" />
            <input type="submit" value="Log in" />
        </form>
    </body>
</html>

models.py:模型.py:

??

views.py:视图.py:

from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login
from django.template import RequestContext


def login_user(request):

    username = password = ""
    state = ""

    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')

        print username, password

        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            state = "Valid account"
        else:
            state = "Inactive account"
    return render_to_response('auth_user/auth.html', RequestContext(request, {'state': state, 'username': username}))

What I am not able to understand?我无法理解什么?

1> I am pretty sure I would have to implement a function in views.py to get the POST values for email and password and validate it, eg: [SO] . 1> 我很确定我必须在views.py实现一个函数来获取emailpasswordPOST值并验证它, 例如: [SO] The documentation specifies to either implement a Search/Bind or Direct Bind.该文档指定实施搜索/绑定或直接绑定。 Why?为什么? If the views.py would contain the actual piece of authentication code, what is the code doing specified in the documentation?如果views.py将包含实际的一段身份验证代码,那么文档中指定的代码是做什么的?

2> If the views.py would perform the actual auth, then why do we need the variable specified in the documentation? 2> 如果views.py会执行实际的身份验证,那么为什么我们需要文档中指定的变量?

3> The author has done a great job with the library, but the documentation does not provide with a simple barebones example of how to implement the entire authentication system with LDAP. 3> 作者在库方面做得很好,但是文档没有提供一个简单的准系统示例,说明如何使用 LDAP 实现整个身份验证系统。 Can anyone please point to such a resource, if it exists?任何人都可以指出这样的资源,如果它存在吗? It is not easy to understand the files that need to be added/modified to implement such a system.要实现这样的系统需要添加/修改哪些文件并不容易理解。

This page might have what you are looking for: https://pypi.python.org/pypi/django-auth-ldap concerning the LDAP backend.此页面可能包含您要查找的内容:关于 LDAP 后端的https://pypi.python.org/pypi/django-auth-ldap You are lucky that one exists, so you don't have to code an auth backend yourself :-)您很幸运,存在一个,因此您不必自己编写身份验证后端 :-)

Basically django.contrib.auth.models already has a User object that contains everything you need about the user.基本上 django.contrib.auth.models 已经有一个 User 对象,它包含你需要的关于用户的一切。 So you don't need to create a new models.py.所以你不需要创建一个新的models.py。

You just need to authenticate yourself in your views.py, in a login function, using您只需要在您的 views.py 中的登录功能中验证您自己,使用

from django.contrib.auth import authenticate, login
user = authenticate(username=request.REQUEST.get('email'), password=request.REQUEST.get('password'))
# handle error cases, inactive users, ...
login(request, user)

If user is None, then authentication failed.如果用户是无,则身份验证失败。 If not, you can explore this object to see what has the backend pulled for you.如果没有,您可以探索此对象以查看后端为您提供了什么。

Then, you can elect to create another model with User as a foreignKey if you want to keep Preferences linked to this User for this application but nor part of the LDAP.然后,如果您希望将此应用程序的首选项链接到此用户,但不属于 LDAP,您可以选择创建另一个模型,并将用户作为外键。

In this case, you will need:在这种情况下,您将需要:

Models.py模型.py

The definition of the data that is important to you based on your application.根据您的应用程序定义对您很重要的数据。 You are going to pull the user data from the LDAP, and fill up this model with it and other preferences linked to the User:您将从 LDAP 中提取用户数据,并用它和链接到用户的其他首选项填充此模型:

from django.contrib.auth.models import User    

class Profile(models.Model):
    """User profile.  Contains some basic configurable settings"""
    user = models.ForeignKey(User, unique=True)
    phone_number = models.CharField(max_length=256, blank=True, default='')
    ...

Views.py视图.py

  • in the login function, if request.method == 'POST', then get_or_create the user profile using the user your just got from authenticate.在登录函数中,如果 request.method == 'POST',则 get_or_create 使用您刚刚从身份验证中获得的用户配置文件。

     profile, profile_is_new = Profile.objects.get_or_create(user=user)

The django-auth-ldap docs are indeed written for developers who are familiar with Django. django-auth-ldap 文档确实是为熟悉 Django 的开发人员编写的。 Also LDAP.还有 LDAP。 If you're starting from scratch, I would recommend taking it one step at a time:如果您是从头开始,我建议您一步一步来:

  1. The Django tutorial Django 教程
  2. Django authentication Django 认证
  3. Some kind of LDAP tutorial, if you're not already familiar.某种 LDAP 教程,如果您还不熟悉的话。
  4. django-auth-ldap django-auth-ldap

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

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