简体   繁体   English

c#检查一个组的用户成员?

[英]c# check if the user member of a group?

I have a code that I use to check if the user is member of the AD, worked perfectly, 我有一个代码,用于检查用户是否是AD的成员,工作得很好,

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)

This is not available on Windows XP or earlier. 这在Windows XP或更早版本中不可用。

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);
    }
}

在ASP.Net中,您将使用Page.User.IsInRole("RoleName")或者在Windows中,您可以使用System.Threading.Thread.CurrentPrincipal.IsInRole("RoleName")

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 它适用于我,它可以用于不属于域控制器/ Active Directory的计算机

Thank you all for the help 谢谢大家的帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM