c# 检查用户是否为组成员? [英] c# check if the user member of a group?

查看:37
本文介绍了c# 检查用户是否为组成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码,用于检查用户是否是 AD 成员,运行良好,

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!

这是我的代码:

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

我想这样做:

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

推荐答案

我用这段代码解决了

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

谢谢大家的帮助

这篇关于c# 检查用户是否为组成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆