[英]LDAP authentication with Django
使用LDAP驗證Django時遇到了一些問題
我正在使用django-auth-ldap
,代碼如下:
view.py
username = ''
password = ''
state = ''
if not request.user.is_authenticated():
if request.method == 'POST':
username = request.REQUEST.get('username')
password = request.REQUEST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
state = "Valid account"
return redirect('/home/')
else:
state = "Inactive account"
return render_to_response('login.html')
else:
return redirect('/home/')
HTML的形式是:
<form action="" method="POST"> {% csrf_token %}
User Name: <input type="text" name="username">
Password: <input type="password" name="password">
<button type="submit">Log on</button>
</form>
並且setting.py是:
AUTH_LDAP_SERVER_URI = "server"
AUTH_LDAP_BIND_DN = "My_DN"
AUTH_LDAP_BIND_PASSWORD = "My_Password"
FILTER_STR = "(&(cn=*%s*)(objectCategory=person)(objectClass=user))" % "%(user)s"
AUTH_LDAP_USER_SEARCH = LDAPSearch("search_words",
ldap.SCOPE_SUBTREE, FILTER_STR)
AUTH_LDAP_CONNECTION_OPTIONS = {
ldap.OPT_DEBUG_LEVEL:1,
ldap.OPT_REFERRALS:0,
}
# Populate the Django user from the LDAP directory.
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail"
}
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
視圖中的authenticate值始終返回None,但我不知道為什么。
有誰能解決我的問題? 或幫助我檢查代碼。
謝謝。
使用auth裝飾器login_required就像:
urls.py:
urlpatterns = patterns('',
# ex: /
url(r'^$', views.index, name='index'),
url(r'^login/$', 'django.contrib.auth.views.login', {
'template_name': 'APPNAME/login.html'
}),
url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', {
# using logout_then_login, no logout template is needed
#'template_name': 'APPNAME/logout.html'
}),
)
views.py:
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
@login_required
def index(request):
msg = "welcome to the index view"
context = {'request': request, 'msg': msg}
return render(request, 'APPNAME/index.html', context)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.