按組訪問我有一個具有兩個應用App1和應用2) 每個應用程序具有僅1視圖Django項目。 。我的項目使用django-auth-ldap連接到openldap。 我有兩個組(Group1,Group2)。Django的限制/允許從LDAP
我之前我在APP1和App2(@login_required)和結果的看法添加裝飾如預期那樣從1與組2的所有用戶將能夠登錄到這兩個應用程序。
我希望能夠只允許GROUP1只能訪問APP1,只有第2組的訪問APP 2。
我嘗試了許多代碼,但我沒有一個工作。
這裏是我的代碼:
app1.views.py
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import views as auth_views
@login_required(login_url='/accounts/login/')
def index(request):
#getting our template
template = loader.get_template('main/index.html')
#rendering the template in HttpResponse
return HttpResponse(template.render())
這裏是settings.py我的LDAP設置:
#Generated by 'django-admin startproject' using Django 1.11.
import os
import django
AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend',)
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
AUTH_LDAP_SERVER_URI = "ldap://mydomain.com"
AUTH_LDAP_BIND_DN = "cn=admin,dc=mydomain,dc=com"
AUTH_LDAP_BIND_PASSWORD = "mypass"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=ou_org_unit,dc=mydomain,dc=com",
ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=ou_org_unit,cn=group1,cn=group2,dc=mydomain,dc=com",
ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"
)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType()
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail"
}
AUTH_LDAP_FIND_GROUP_PERMS = True
AUTH_LDAP_CACHE_GROUPS = True
AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600
謝謝你的回覆。我試過你的代碼,現在我根本無法登錄。我想我需要一種方法來檢查組名 – Eyla
我發現這個:https://django-auth-ldap.readthedocs.io/en/stable/users.html#direct-attribute-access(請參閱頁面底部)。您可以從屬性映射中刪除''ldap_group「:」cn「',並將組檢查修改爲像'hasattr(u,'ldap_user')和u.ldap_user.group_names'中的group_name。你必須稍微玩一下,但看起來好像獲得用戶所在的組的列表是可能的。 – mindcruzer
我試過你的解決方案,但仍然沒有結果,沒有錯誤,我無法登錄,我嘗試了不同的配置,總是得到相同的結果 – Eyla