Active Directory PrincipalContext.ValidateCredentials域消除歧义
我正在处理两个域 – 一个是可信域。 一个域上可能有JohnSmith,另一个域上可能有另一个JohnSmith。 这两个人都需要登录我的应用程序。
我的问题:我传入哪个域无关紧要 – 此代码返回true! 我怎么知道JohnSmith正在登录哪个?
static public bool CheckCredentials( string userName, string password, string domain) { using (var context = new PrincipalContext(ContextType.Domain, domain)) { return context.ValidateCredentials(userName, password); } }
ValidateCredentials
与userPrincipalName
您可以尝试构建组合登录和域的第一个参数(用户名),以创建用户名JohnSmith@dom1.com
与JohnSmith@dom2.com
。
您始终可以检索已登录的用户的完整DN
UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName); up.UserPrincipalName // shows user@domain.com up.DistinguishedName // shows CN=Surname,OU=group,DC=domain,DC=com up.SamAccountName // shows login name
使用up.SamAccountName来跟随对ValidateCredentials的调用,包括域名 – 毕竟你不能让2个用户使用相同的sAMAccountName登录!
DistinguishedName肯定会告诉你JohnSmith登录的是哪个。
根据JPBlanc的回答,我重写了我的代码。 我还添加了一个try / catch,以防传入虚假域名。
static public bool CheckCredentials( string userName, string password, string domain) { string userPrincipalName = userName + "@" + domain + ".com"; try { using (var context = new PrincipalContext(ContextType.Domain, domain)) { return context.ValidateCredentials(userPrincipalName, password); } } catch // a bogus domain causes an LDAP error { return false; } }
对于包含其中不同电子邮件地址的域,接受的答案将失败。 例:
Domain = Company User1 = employee@department1.com (under company Domain) User2 = employee2@Department2.com (under company Domain)
提供的答案将返回false,使用:
userName = "employee"; domain = "company"; string userPrincipalName = userName + "@" + domain + ".com";
跨域包含用户的正确方法是:
string userPrincipalName = userName + "@" + domain;
如果没有.com部分,它会在该域中搜索用户,而不是在全局域中搜索电子邮件。