我在跑AD 驗證時有些帳號會顯示ArgumentOutOfRangeException
但有些不會
我在想是不是我在抓Filter 成功的才不會顯示嗎
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, password);
search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" +userName+ ")";
search.PropertiesToLoad.AddRange(new string[] { "sn", "givenName", "displayName", "title", "department" });
result = search.FindOne();<-這裡就會throw ex出來
求解各位大神了
我發現我AD的帳號 "title", "department" 沒輸入值 不知道這樣抓會不會出錯呢
但我嘗試把PropertiesToLoad 改掉search.PropertiesToLoad.AddRange(new string[] { "sn", "givenName", "displayName"});
相同帳號還是會throw ex出來
都是一樣的問題
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index.
//如果是Filter 出錯我改這樣有用嗎,還是有哪些方式可以讓我Debbug的方式呢search.Filter = "(SAMAccountName=" +"*"+userName+"*"+")";
以下補充我原始碼:
public LDAPDto LDAPLogin1(string userName, string mima)//驗證DomainName
{
string domainName = System.Configuration.ConfigurationManager.AppSettings["LDAPDomainName"];
string _path = System.Configuration.ConfigurationManager.AppSettings["LDAPPath"];
PrincipalContext ADCHECK = new PrincipalContext(ContextType.Domain, domainName);
if (!ADCHECK.ValidateCredentials(userName, mima, ContextOptions.Negotiate))
{
return new LDAPDto() { IsLogin = false };
}
string domainAndUsername = domainName + @"\" + userName;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, mima);
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + userName + ")";
search.PropertiesToLoad.AddRange(new string[] { "sn", "givenName", "displayName", "title", "department" });
SearchResult result = search.FindOne();
result.GetDirectoryEntry();
var user = new LDAPDto()
{
IsLogin = true,
Img = null,
Sn = (string)result.Properties["sn"][0],
Title = (string)result.Properties["title"][0],
GivenName = (string)result.Properties["givenName"][0],
DisplayName = (string)result.Properties["displayName"][0],
Department = (string)result.Properties["department"][0],
};
return user;
}
#回應 @japhenchen 留言
所以我不需要去做search.Filter = "(SAMAccountName=" + userName + ")";
的動作嗎
我的
static public bool ValidUser(string username, string password)
{
bool result = false;
try
{
string activeDirectoryServerDomain = "yourcomany.com";
DirectoryEntry de = new DirectoryEntry("LDAP://" + activeDirectoryServerDomain, username + "@" + activeDirectoryServerDomain, password, AuthenticationTypes.Secure);
DirectorySearcher ds = new DirectorySearcher(de);
ds.FindOne();
//建議在此檢查人事資料及資料庫相關權限
result = true;
}
catch //(Exception ex)
{
result = false;
}
return result;
}
bb77a88bb
我的做法只是驗證帳號密碼是否確實存在且有效而已,就放個try .. catch .. 來驗證,帳號不存在或密碼錯誤,都會raise excetion,有exception就return false,反之true
了解但是目前我狀況蠻怪異的,我帳號驗證都能成功,但是就不知道為啥會卡在FindOne();這裡
// 綁定域
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://dc=yourdomain,dc=com");
// 取得用戶資訊
UserPrincipal user = UserPrincipal.FindByIdentity(pc, "cn=John Doe");