按组访问我有一个具有两个应用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