[英]Active Directory PrincipalContext.ValidateCredentials domain disambiguation
I'm dealing with two domains - one is a trusted domain. 我正在处理两个域 - 一个是可信域。 There may be a JohnSmith on one domain and another JohnSmith on the other. 一个域上可能有JohnSmith,另一个域上可能有另一个JohnSmith。 Both of these people need to log into my application. 这两个人都需要登录我的应用程序。
My problem: it doesn't matter which domain I pass in - this code returns true! 我的问题:我传入哪个域并不重要 - 这段代码返回true! How do I know which JohnSmith is logging in? 我怎么知道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
。
You can always retrieve the full DN of the user who has logged in using 您始终可以检索已登录的用户的完整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
Use the up.SamAccountName to subsequent calls to ValidateCredentials including the domain name - you can't have 2 users who log in using the same sAMAccountName after all! 使用up.SamAccountName对ValidateCredentials的后续调用(包括域名) - 您不能让2个用户使用相同的sAMAccountName登录!
The DistinguishedName will definitely show you which JohnSmith logged in. DistinguishedName肯定会告诉你JohnSmith登录的是哪个。
Based on JPBlanc's answer, I've re-written my code. 基于JPBlanc的回答,我重写了我的代码。 I've also added a try/catch in case a bogus domain is passed in. 我还添加了一个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;
}
}
The accepted answer will fail with Domains that contain different email addresses within them. 对于包含不同电子邮件地址的域,接受的答案将失败。 Example: 例:
Domain = Company
User1 = employee@department1.com (under company Domain)
User2 = employee2@Department2.com (under company Domain)
The provided answer will return false using: 提供的答案将返回false,使用:
userName = "employee";
domain = "company";
string userPrincipalName = userName + "@" + domain + ".com";
The correct way to encompass users across domains is: 跨域包含用户的正确方法是:
string userPrincipalName = userName + "@" + domain;
without the .com portion it searches the user AT that domain instead of searching for an email within a global domain. 如果没有.com部分,它会在该域中搜索用户,而不是在全局域中搜索电子邮件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.