您还需要遍历用户所属的组,并检查它是否与您也想授予访问权限的组匹配。
首先你需要加载用户,然后你需要遍历“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 获取我的 AD 连接字符串
ConfigurationManager.ConnectionStrings["ADConnectionString"].ConnectionString
网络配置
<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")
检查此链接以获取更多信息:
搜索组