首先,需引入ldap3和django-python3-ldap 模块;
配置方法如下:
1、django目录下的settings.py文件,增加ldap服务配置:
AUTHENTICATION_BACKENDS = (
"django_python3_ldap.auth.LDAPBackend", # 优先使用ldap认证
'django.contrib.auth.backends.ModelBackend',
)
LDAP_AUTH_URL = 'ldap://192.168.2:389' # ldap服务器地址
LDAP_AUTH_USE_TLS = False
LDAP_AUTH_SEARCH_BASE = 'ou=People,dc=test,dc=com'
LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson"
LDAP_AUTH_USER_FIELDS = {
"username": "cn",
"email": "mail"
}
LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data"
LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations"
LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters"
LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_openldap"
2、新建auth.py文件,实现ldap连接和验证函数:
import ldap3
def auth_user(user, passwd):
# conn = ldap.initialize("ldap://192.168.2:389") #python2使用ldap库可用此方法
s="ldap://192.168.2:389"
try:
conn = ldap3.Connection(
ldap3.Server(s, get_info=ldap3.NONE, allowed_referral_hosts=[("*", True)], ),
user=user, password=passwd, auto_bind=ldap3.AUTO_BIND_NO_TLS, raise_exceptions=True)
conn.open()
conn.bind()
return 1
except:
return 0
3、models.py里创建User模型和login方法:
class User(models.Model):
# 如果没有models.AutoField,默认会创建一个id的自增列
name = models.CharField("用户名", max_length=32, unique=True)
password = models.CharField("密码", max_length=128)
email = models.CharField("邮箱", null=True, max_length=32)
create_time = models.DateTimeField("创建时间", null=True, auto_now_add=True)
update_time = models.DateTimeField("更新时间", null=True, auto_now=True)
@classmethod
def login(cls, name, password):
dn='cn='+name+',ou=people,dc=test,dc=com'
ret = auth_user(dn, password)
if ret:
try:
user = User.objects.get(name=name)
return user
except ObjectDoesNotExist as e:
pw_md5_obj = hashlib.md5() #创建一个MD5对象
pw_md5_obj.update(password) #添加去要加密的文本
md5_pw = pw_md5_obj.hexdigest()
user = User(name = name,email=name+"@test.com",password=md5_pw)
user.save()
return user
else:
return None
4、views.py文件中编写login函数,思路:优先查询数据库中是否存在该用户,并验证,若数据库中不存在该用户,再连接ldap进行认证。
def login(request):
if request.method == 'POST':
name = request.POST.get('name')
psw = request.POST.get('password')
user = User.objects.filter(name=name).first()
if user:
check = check_password(psw, user.password)
if check: # 如果数据库里有记录(即与数据库里的数据相匹配或者对应或者符合)
session = request.session
session['un'] = name
session['ri'] = user.role_id
session['is_login'] = True
return JsonResponse({'status': 'OK', 'un': name, 'ri': user.role_id, 'is_login': True})
else:
user = User.login(name, psw)
if user!=None:
session = request.session
session['un'] = name
session['ri'] = user.role_id
session['is_login'] = True
return JsonResponse({'status': 'OK', 'un': name, 'ri': user.role_id, 'is_login': True})
else:
return JsonResponse({'status': '用户名或密码错误!'})
else:
return JsonResponse({'status': '用户名或密码错误!'})
else:
return render(request, 'login.html')
以上,django实现ldap认证登录完成。
网友评论