2016-04-26 82 views
1

我正在嘗試爲django項目配置ldap身份驗證。所有用戶都應該能夠訪問Web服務(我實現了這一點)。我想讓幾個人(ldap集團的一部分)成爲管理員。我需要驗證登錄用戶是否屬於ldap組。django-auth-ldap - 查找用戶是否屬於ldap組

我沒有使用Django默認身份驗證後端,也沒有計劃使用。

有沒有簡單的方法來查找用戶是否屬於特定的ldap組?

我試圖閱讀和理解「https://pythonhosted.org/django-auth-ldap/index.html」,但它是在非常高的水平,沒有例子。

+0

你有沒有你的代碼? –

回答

0

我的問題解決了。

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})