2012-02-27 75 views
3

我正在处理两个域 - 一个是受信任的域。在另一个域上可能有JohnSmith,而另一个域上可能有另一个JohnSmith。这两个人都需要登录到我的应用程序。Active Directory PrincipalContext.ValidateCredentials域消歧

我的问题:我传入哪个域并不重要 - 此代码返回true! 我如何知道John Smith正在登录?

static public bool CheckCredentials(
     string userName, string password, string domain) 
    { 
     using (var context = new PrincipalContext(ContextType.Domain, domain)) 
     { 
      return context.ValidateCredentials(userName, password); 
     } 
    } 

回答

2

根据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; 
     } 
    } 
0

接受的答案将失败,并包含在其中不同的电子邮件地址域。例如:

Domain = Company 

User1 = [email protected] (under company Domain) 

User2 = [email protected] (under company Domain) 

所提供的答案将使用返回false:

userName = "employee"; 
domain = "company"; 
string userPrincipalName = userName + "@" + domain + ".com"; 

的正确方法包括跨多个域的用户是:

string userPrincipalName = userName + "@" + domain; 

而不.com部分它搜索用户在该域中,而不是在全局域中搜索电子邮件。

3

您可以随时获取用户的完整DN谁在使用

UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName); 
up.UserPrincipalName // shows [email protected] 
up.DistinguishedName // shows CN=Surname,OU=group,DC=domain,DC=com 
up.SamAccountName // shows login name 

使用up.SamAccountName后续调用ValidateCredentials包括域名记录 - 你不能谁登录用户毕竟在使用相同的sAMAccountName!

DistinguishedName肯定会告诉你哪个JohnSmith登录。