gpt4 book ai didi

c# - .net C# 中的 Ldap 连接

转载 作者:行者123 更新时间:2023-11-30 21:03:21 24 4
gpt4 key购买 nike

我有一个可以发送电子邮件的应用程序。现在要求使用 ldap 来验证用户电子邮件。我对这个概念很陌生。我已获得 ldap 服务器链接。不知道如何进行。任何文章或命中都会有很大帮助。

这是我正在尝试的代码

public static UserDetail GetUserDetails(string EmailId, string domainName)
{
UserDetail userDetail = new UserDetail();

try
{
string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", EmailId);
string[] properties = new string[] { "fullname" };

DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domainName, null, null, AuthenticationTypes.Secure);
DirectorySearcher searcher = new DirectorySearcher(adRoot);
searcher.SearchScope = SearchScope.Subtree;
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.PropertiesToLoad.AddRange(properties);
searcher.Filter = filter;
SearchResult result = searcher.FindOne();

DirectoryEntry directoryEntry = result.GetDirectoryEntry();
string displayName = directoryEntry.Properties["displayName"[0].ToStrin();
string firstName = directoryEntry.Properties["givenName"][0].ToString();
string lastName = directoryEntry.Properties["sn"][0].ToString();
string emailId = directoryEntry.Properties["mail"][0].ToString();

userDetail.EmailId = emailId;
}
catch (Exception)
{

}
return userDetail;
}

我想通过点击搜索按钮来实现它。如何调用方法和传递变量。

最佳答案

如果您使用的是 .NET 3.5 或更新版本,则可以使用 PrincipalSearcher 和“query-by-example”主体进行搜索:

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a UserPrincipal
// and with the e-mail of "bruce@example.com"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.EmailAddress = "bruce@example.com";

// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

// try to find that user
UserPrincipal found = srch.FindOne() as UserPrincipal;

if(found != null)
{
// do whatever here - "found" is the user that matched the e-mail given
}
else
{
// there wasn't any user with that e-mail address in your AD
}

如果您还没有-绝对阅读 MSDN 文章 Managing Directory Security Principals in the .NET Framework 3.5它很好地展示了如何充分利用 System.DirectoryServices.AccountManagement 中的新功能。或者查看 MSDN documentation on the System.DirectoryServices.AccountManagement命名空间。

当然,根据您的需要,您可能希望在您创建的“按示例查询”用户主体上指定其他属性:

  • DisplayName(通常:名字 + 空格 + 姓氏)
  • SAM 帐户名 - 您的 Windows/AD 帐户名
  • User Principal Name - 您的“username@yourcompany.com”样式名称

您可以在 UserPrincipal 上指定任何属性,并将它们用作您的 PrincipalSearcher 的“按示例查询”。

关于c# - .net C# 中的 Ldap 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12949421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com