我正在尝试为 Django 项目配置 LDAP 身份验证。所有用户都应能够访问 Web 服务(已实现此目标)。我想将几个人(LDAP 组的一部分)作为管理员。我需要验证登录用户是否属于 LDAP 组。
我没有使用 Django 默认的身份验证后端,也不打算使用。
是否有任何简单的方法来查找用户是否属于特定的 LDAP 组?
我尝试阅读和理解 "https://pythonhosted.org/django-auth-ldap/index.html",但它是非常高级而且没有示例。
我的问题已经解决。
settings.py:
AUTH_LDAP_SERVER_URI = "ldap://ldap.mycompany.com"
AUTH_LDAP_USER_DN_TEMPLATE = "CN=%(user)s,OU=Employees,OU=mycompany Users,DC=dev,DC=mycompany,DC=com"
AUTHENTICATION_BACKENDS = ['django_auth_ldap.backend.LDAPBackend']
# Set up the basic group parameters.
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("CN=%(user)s,OU=Employees,OU=mycompany Users,DC=dev,DC=mycompany,DC=com",
ldap.SCOPE_SUBTREE, "(objectClass=top)" #updated objectClass=top, it was groupOfNames
)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="CN") #added argument name_attr="CN"
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenname",
"last_name": "sn",
"email": "mail"
}
AUTH_LDAP_PROFILE_ATTR_MAP = {"home_directory": "homeDirectory"}
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"is_active": "CN=activeGroup,OU=Standard,OU=mycompany Groups,DC=dev,DC=mycompany,DC=com",
"is_staff": "CN=staffGroup,OU=Standard,OU=mycompany Groups,DC=dev,DC=mycompany,DC=com",
"is_superuser": "CN=GROUPNAME,OU=AnwenderRollen,OU=Gruppen,ou=XXX,ou=XXX,dc=XXX,dc=XXX,dc=XXX"
}
### Added all below lines
# Use LDAP group membership to calculate group permissions.
AUTH_LDAP_FIND_GROUP_PERMS = True
# Cache group memberships for an hour to minimize LDAP traffic
AUTH_LDAP_CACHE_GROUPS = True
AUTH_LDAP_GROUP_CACHE_TIMEOUT = 1 #3600
AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True
views.py:
def login_view(request):
username = ""
password = ""
state = ""
if request.method == "POST":
username = request.POST.get('cec')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request,user)
return redirect('/homepage')
print "user.is_active:", user.is_active
print "user.is_staff:", user.is_staff
print "user.is_superuser:", user.is_superuser
else:
state = "Invalid Credentials !!!"
return render(request,'testapp/loginpage.html',{'state':state})