c# check if the user member of a group?

2020-02-05 02:37发布

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!

what do I need to modify to achieve that, I did some work, but it fails!

so here is my code:

        //Authenticate a User Against the Directory
        private bool Authenticate(string userName,string password, string domain)
        {

            if (userName == "" || password == "")
            {
                return false;
            }

            bool authentic = false;
            try
            {
                DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain,userName, password);
                object nativeObject = entry.NativeObject;
                authentic = true;
            }
            catch (DirectoryServicesCOMException) { }
            return authentic;
        }

I want to make it like this:

private bool Authenticate(string userName,string password, string domain, string group)

3条回答
够拽才男人
2楼-- · 2020-02-05 03:05

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

查看更多
家丑人穷心不美
3楼-- · 2020-02-05 03:23

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);
    }
}
查看更多
对你真心纯属浪费
4楼-- · 2020-02-05 03:24

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

查看更多
登录 后发表回答