了解Django-LDAP认证 [英] Understanding Django-LDAP authentication

查看:193
本文介绍了了解Django-LDAP认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django的新手,已经被分配了实施用户身份验证系统的任务,LDAP作为后端。我猜想文档假定最终开发人员在Django有足够的经验能够理解和实施这样一个系统。这是我不了解如何使用基于LDAP的身份验证实现简单的django应用程序的地方。这是我迄今为止所了解的:



只将更改发布到文件中:

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

AUTH_LDAP_SERVER_URI =ldap://<我的网址>
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

 < html> 
< head>
< title>登录< / title>
< / head>
< body>
{{state}}
< form action =method =post> {%csrf_token%}
电子邮件地址:< input type =textname =emailvalue ={{email}}/>
密码:< input type =passwordname =passwordvalue =/>
< input type =submitvalue =登录/>
< / form>
< / body>
< / html>

models.py:

 

views.py:

从django.contrib.auth导入验证,登录
从django.template导入RequestContext


def login_user(request):

username = password =
state =

如果request.POST:
username = request.POST。 get('username')
password = request.POST.get('password')

打印用户名,密码

user = authenticate(username = username,
登录(请求,用户)
状态=有效帐户
其他:
状态=非活动帐户
return render_to_response('auth_user / auth.html',RequestContext(request,{'state':state,'username':username}))

我不明白什么?



1>我很确定我必须在 views.py 中实现一个函数来获取 POST 电子邮件密码的值,并验证它,例如:[SO] 。该文档规定了实现搜索/绑定或直接绑定。为什么?如果 views.py 将包含实际的验证码,文档中指定的代码是什么?



2>如果 views.py 将执行实际的验证,那么为什么我们需要指定的变量文件?



3>作者在图书馆方面做得非常出色,但文档并没有提供如何使用LDAP实现整个身份验证系统的简单准则。任何人都可以指出这样的资源,如果存在的话?了解需要添加/修改以实现这样的系统的文件是不容易的。

解决方案

此页面可能您正在寻找什么:关于LDAP后端的 http://pythonhosted.org/django-auth-ldap/ 。你很幸运有一个存在,所以你不必自己编写一个auth后端: - )



基本上django.contrib.auth.models已经有一个User对象其中包含用户需要的一切。所以你不需要创建一个新的models.py。



你只需要在你的views.py中,在登录功能中使用


  from django.contrib.auth import authenticate,login 
user = authenticate(username = request.REQUEST.get('email' ),password = request.REQUEST.get('password'))
#处理错误情况,非活动用户,...
登录(请求,用户)

如果用户为None,则身份验证失败。如果没有,您可以探索这个对象来查看后端为您提供的内容。



然后,您可以选择创建另一个用户作为外键的模型,如果你想保持与本用户的首选项相关联,但不包括LDAP。



在这种情况下,您将需要:



Models.py



根据您的应用程序对您重要的数据定义。您将从LDAP中拉取用户数据,并使用该模型填充该模型以及与用户相关联的其他首选项:

  from django.contrib.auth.models import User 

class Profile(models.Model):
用户个人资料包含一些基本的可配置设置
用户= models.ForeignKey(User,unique = True)
phone_number = models.CharField(max_length = 256,blank = True,default ='')
...

Views.py




  • 在登录功能中,如果request.method =='POST',则使用您刚刚从验证的用户get_or_create用户配置文件。

     个人资料,profile_is_new = Profile.objects.get_or_create(user = user)



    • I am new to Django and have been assigned the task of implementing a user authentication system with LDAP as the backend. I guess the documentation assumes that the end developer has enough experience in Django to be able to understand and implement such a system. This is where I fail to understand how to implement a simple django application with LDAP based authentication. 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

      <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:

      ??
      

      views.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, e.g: [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?

      2> If the views.py would perform the actual auth, then why do we need the variable specified in the documentation?

      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. 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: http://pythonhosted.org/django-auth-ldap/ concerning the LDAP backend. 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. So you don't need to create a new models.py.

      You just need to authenticate yourself in your views.py, in a login function, using

      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.

      In this case, you will need:

      Models.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:

      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

      • in the login function, if request.method == 'POST', then get_or_create the user profile using the user your just got from authenticate.

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

      这篇关于了解Django-LDAP认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆