c#检查一个组的用户成员?
我有一个代码,用于检查用户是否是AD的成员,工作得很好,
现在我想添加检查用户是否也是组成员的可能性!
我需要修改什么来实现这一点,我做了一些工作,但它失败了!
所以这是我的代码:
//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)
这在Windows XP或更早版本中不可用。
无论如何,为了检查组成员身份,您可以使用以下代码:
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")
我用这段代码解决了这个问题
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; }
它适用于我,它可以用于不属于域控制器/ Active Directory的计算机
谢谢大家的帮助
- DirectoryServices UserPrincipal.SetPassword忽略密码策略(密码历史记录)
- 如何获取域控制器IP地址
- 使用ASP.NET获取Active Directory信息,无需用户名和密码
- Active Directory检查用户是否已登录
- System.DirectoryServices很慢?
- ASP.NET – 获取DirectoryEntry / SID的主体/相对标识符(RID)
- 如何通过ldap中的域名获取用户的用户名和SID
- C# – 查找Active Directory用户的所有电子邮件地址
- 在ASP.NET webapp中,FindByIdentity因PricipalOperationException而失败