
[英]Enumerating AD Security Group memberships for a User in ASP.Net 5/core?
[英]Filtering by an AD Security Group in ASP.NET
我有一个Visual Studio 2010中开发的ASP.NET应用程序,它使用使用本机身份验证控件的.NET Framework版本4。 我已经使用Active Directory成员资格提供程序连接了该站点。
我的连接字符串如下所示:
connectionString="LDAP://MYDC-004/DC=company,DC=corp,DC=pvt"
这很有效,因为登录页面可以正常工作,并且AD中存在的任何用户都可以使用其凭据登录。
但是,我只希望允许一个特定安全组中的用户登录。我知道安全组(称为“ GR-DwgDep-Admins”)在AD组织单位中的位置,因此我想到了此修改后的连接字符串:
connectionString="LDAP://MYDC-004/CN=GR-DwgDep-Admins,OU=Groups,OU=Division,DC=company,DC=corp,DC=pvt" />
当我尝试登录时(并且我肯定属于该组),出现的错误是“无法在指定的容器中创建用户对象”。
我的语法不正确吗? 还是我在概念上做错了方法? 我真的更喜欢通过连接字符串设置来执行此操作,因为这样,现有的.NET登录控件将按原样使用它。
我将不胜感激任何人的任何建议。 谢谢!
您还需要遍历用户所属的组,并检查它是否也与您要授予访问权限的组匹配。
首先,您需要加载用户,然后循环浏览“ memberOf”集合,并检查它们是否属于指定的组。
//Get connectionstring from web.config and initialize directory entry to search for groups user belongs to
DirectoryEntry de = new DirectoryEntry(ConfigurationManager.ConnectionStrings["ADConnectionString"].ConnectionString);
//Specify that we want to find the groups
DirectorySearcher ds = new DirectorySearcher(de, "(objectCategory=group)");
//Filter by user and specify what data to return
ds.Filter = String.Format("(&(SAMAccountName={0}))", model.UserName);
ds.PropertiesToLoad.Add("sAMAccountName");
ds.PropertiesToLoad.Add("memberOf");
//Loop though all results
foreach (SearchResult sr in ds.FindAll())
{
//Get the properties available and loop through "memberof"
DirectoryEntry desr = sr.GetDirectoryEntry();
ResultPropertyCollection myResultPropColl = sr.Properties;
//Get a key
foreach (string myKey in myResultPropColl.PropertyNames)
{
//Check the key that we are using "memberof"
if (myKey.ToLower() == "memberof")
{
//Loop through all items for given key
foreach (System.String myCollection in myResultPropColl[myKey])
{
//Check if we have a match
if (myCollection.Contains("Web - Internal Admin"))
{
//Success
de.Dispose();
desr.Dispose();
//Do something
}
}
}
}
}
对于第一行,我从web.config获取我的广告连接字符串
ConfigurationManager.ConnectionStrings["ADConnectionString"].ConnectionString
web.config中
<add name="ADConnectionString" connectionString="LDAP://ua.local/DC=ua,DC=local" />
然后,我将获取组并通过特定的用户名对其进行过滤。 然后,我为sAMAccountName和memberOf指定返回值。 在此示例中,获取sAMAccountName不是必需的。
DirectorySearcher ds = new DirectorySearcher(de, "(objectCategory=group)");
//Filter by user and specify what data to return
ds.Filter = String.Format("(&(SAMAccountName={0}))", model.UserName);
ds.PropertiesToLoad.Add("sAMAccountName");
ds.PropertiesToLoad.Add("memberOf");
其余的内容很容易理解。 遍历结果并检查“ memberof”键。 找到后,使用“ memberof”键并遍历其值,并检查其是否与您所需的组匹配。
if (myKey.ToLower() == "memberof")
检查此链接以获取更多信息: 搜索组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.