I met some problem when I authenticate Django with LDAP
I am using django-auth-ldap
and codes are below:
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/')
and the form in HTML is:
<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>
and the setting.py is:
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',
)
The authenticate value in view always return None, but I don't know why.
Is there anyone who can solve my problem? Or help me to check my codes.
Thank you.
use auth decorator login_required like:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.