How to check if a user exists on LDAP(如何检查用户是否存在于 LDAP 上)
问题描述
我需要仅使用用户名而非密码来验证公司中的用户.
I need to verify users in the company using only their username - not their password.
所以我需要这样的方法
public bool UserExists(string username)
{ ... }
我知道 System.DirectoryServices 命名空间,但不知道从哪里开始.
I am aware of the System.DirectoryServices namespace but don't know where to start.
有什么想法吗?
有 80,000 多条记录,因此请记住这一点.
There are 80,000+ records so try to bear that in mind.
谢谢.
我已经完成了 - 我的代码是:
I have done it - my code is:
private bool UserExists(string userName, string domain)
{
try
{
DirectoryEntry.Exists("WinNT://" + domain + ".[hidden].com/" + userName);
return true;
}
catch (COMException)
{
return false;
}
}
我不知道它是否正确,但它似乎到目前为止有效.
I don't know if it is correct, but it seems to work so far.
迈克尔的回答有两个相关部分:
Michael's answer has two relevant parts:
- http://www.codeproject.com/KB/system/everythingInAD.aspx#22
- http://www.codeproject.com/KB/system/everythingInAD.aspx#35
更新 #2:
我实际使用过这个:
public static bool LoggedOnUserExists()
{
var domain = new PrincipalContext(ContextType.Domain);
UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, Environment.UserName);
return foundUser != null;
}
推荐答案
在 .NET 3.5 及更高版本中,您可以非常简单地使用 System.DirectoryServices.AccountManagement 命名空间:
In .NET 3.5 and up, you can use the System.DirectoryServices.AccountManagement namespaces to do this quite simply:
public bool UserExists(string username)
{
// create your domain context
using (PrincipalContext domain = new PrincipalContext(ContextType.Domain))
{
// find the user
UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username);
return foundUser != null;
}
}
这将适用于常规用户名 John Doe,或者您也可以使用用户的电子邮件地址 (john.doe@company.com),或者他的专有名称 (CN=John Doe) - 看看 IdentityType 枚举必须提供什么 :-)
This will work with the regular user name John Doe, or alternatively you can use the user's e-mail address (john.doe@company.com), or his distinguished name (CN=John Doe) - see what the IdentityType enumeration has to offer :-)
这篇关于如何检查用户是否存在于 LDAP 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查用户是否存在于 LDAP 上
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 将数据集转换为列表 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
