我正在尝试为django项目配置ldap身份验证。所有用户都应该能够访问Web服务(我实现了这一点)。我想做几个人(ldap组的一部分)作为管理员。我需要验证登录用户是否属于ldap组。
我没有使用Django默认身份验证后端,也没有计划使用。
有没有简单的方法来查找用户是否属于特定的ldap组?
我试着阅读并理解" https://pythonhosted.org/django-auth-ldap/index.html"但它处于非常高的水平,没有例子。
答案 0 :(得分:1)
我的问题解决了。
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})