2012-02-27 72 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登錄。