查找用户是否属于组

时间:2018-11-09 14:00:12

标签: c# active-directory

我想查找用户是否属于AD组。您能建议我如何使用以下代码添加该功能吗?

我要求用户(通过表单)输入用户名和密码,所以不要使用Windows凭据。使用下面的代码,我可以通过传递用户名和密码来验证用户。如何建立代码以检查用户是否在广告组中。还有另一种方法吗?请指教

System.Data

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAINNAME");

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

 // find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

if(user != null)
{
   // check if user is member of that group
   if (user.IsMemberOf(group))
   {
     // do something.....
   } 
}

还要查看:How to check if a user belongs to an AD group?

答案 1 :(得分:0)

这是我解决此问题的方法:

            DirectoryEntry adsEntry = new DirectoryEntry("domain", userid, password);
            DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry);
            adsSearcher.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + userid + "))";

        try
        {
            SearchResult adsSearchResult = adsSearcher.FindOne();
            string propertyName = "memberOf";
            ResultPropertyValueCollection rpvcResult = adsSearchResult.Properties[propertyName];

            foreach (Object PropertyValue in rpvcResult)
            {
                if (PropertyValue.ToString() == "Group Name")
                {
                    user.Verified = true;
                    user.FullName = GetFullName(userid);
                    adsEntry.Close();
                } else
                {
                    user.Verified = false;
                    user.error = "You do not belong to the Group so you cannot do this function";
                }
            }

        } catch (Exception ex)
        {
            user.error = "Please check your username and password credentials";
            adsEntry.Close();
        }