c# check if the user member of a group?

前端 未结 3 703
萌比男神i
萌比男神i 2020-12-09 18:17

I have a code that I use to check if the user is member of the AD, worked perfectly,

now I want to add the possibility to check if the user also a member of a group!

相关标签:
3条回答
  • 2020-12-09 18:50

    I solve it with this code

    public bool AuthenticateGroup(string userName, string password, string domain, string group)
        {
    
    
            if (userName == "" || password == "")
            {
                return false;
            }
    
            try
            {
                DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, password);
                DirectorySearcher mySearcher = new DirectorySearcher(entry);
                mySearcher.Filter = "(&(objectClass=user)(|(cn=" + userName + ")(sAMAccountName=" + userName + ")))";
                SearchResult result = mySearcher.FindOne();
    
                foreach (string GroupPath in result.Properties["memberOf"])
                {
                    if (GroupPath.Contains(group))
                    {
                        return true;
                    }
                }
            }
            catch (DirectoryServicesCOMException)
            {
            }
            return false;
        }
    

    it works fine for me, and it can be use with a machine not part of the Domain Controller / Active Directory

    Thank you all for the help

    0 讨论(0)
  • 2020-12-09 18:56

    In ASP.Net you will use Page.User.IsInRole("RoleName") or in Windows you can use System.Threading.Thread.CurrentPrincipal.IsInRole("RoleName")

    0 讨论(0)
  • 2020-12-09 19:09

    This is not available on Windows XP or earlier.

    Anyway, in order to check for group membership, you can use this code:

    bool IsInGroup(string user, string group)
    {
        using (var identity = new WindowsIdentity(user))
        {
            var principal = new WindowsPrincipal(identity);
            return principal.IsInRole(group);
        }
    }
    
    0 讨论(0)
提交回复
热议问题