如何检查用户是否是AD C#中的通讯组列表/安全组的成员

问题描述 投票:2回答:3

我正在使用下面的代码来检查给定的用户是否属于AD中的通讯组。

static bool IsUserMemberOf(string userName, string groupName)
{
  using (var ctx = new PrincipalContext(ContextType.Domain))
  using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName))
  using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, userName))
  {
    return userPrincipal.IsMemberOf(groupPrincipal);
  }
}

我正在调用上述方法,其值为IsUserMemberOf("domain\\username","domain\\groupname")但是我看到一个空指针异常,因为groupPrincipal具有空值。

这方面有帮助吗?

c# active-directory active-directory-group
3个回答
1
投票

仅表示:

groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName)) 

返回空指针,因为您的域中不存在您的组。您只需要测试var ctxuserPrincipalgroupPrincipal


0
投票

实际上,我的网上论坛与我要查询的用户不在同一个域中:我对程序进行了以下更改,现在可以工作。

而且我这样打电话:

IsUserMemberOf("domain1\\username","domain2\\groupname")


static bool IsUserMemberOf(string userName, string groupName)
{
 using (var ctx = new PrincipalContext(ContextType.Domain,"domain1"))
 using (var groupPrincipal = GroupPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain,"domain2"), groupName))
 using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, userName))
 {
    return userPrincipal.IsMemberOf(groupPrincipal);
 }

}


0
投票

//如何检查用户是否在AD成员和特定的AD组成员中

//This Reference and DLL must be attach in your project         
//using System.DirectoryServices.AccountManagement;        


         public bool IsAuthenticated(string username, string pwd)
        {

            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "xxx.com"))   // Your Domain Name
            {
                if (pc.ValidateCredentials(username, password))  //User and Password is OK for Active Directory 
                {
                    UserPrincipal user = UserPrincipal.FindByIdentity(pc, username);  //Get User Active Directory Information Details
                    if (user != null)
                    {

                        var groups = user.GetAuthorizationGroups();   // Get User Authorized Active Directory Groups
                        foreach (GroupPrincipal group in groups)
                        {
                            if (group.Name.Equals("SpecificActiveDirectoryGroupName"))  //Check if user specific group members
                            { 
                                return true;
                            }

                        }
                    }
                }
            }
            return false;
        }
© www.soinside.com 2019 - 2024. All rights reserved.