[英]Active directory authentication using vpn in c#
我正在開發一個Web應用程序,用於根據Active Directory服務器對用戶進行身份驗證。 現在如果我從該AD服務器域下的開發PC運行我的代碼,我的代碼運行順利。 我們需要使用VPN從完全不同的網絡運行代碼,這里開發PC不在那個AD中。 嘗試訪問AD服務器時出現以下錯誤。
指定的域不存在或無法聯系。
我的VPN工作正常。 我可以使用此VPN訪問遠程桌面。 我知道需要一些調整來解決問題,但找不到它。 我通過以下鏈接但找不到任何解決方案。
以下是我在web.config
設置
<appSettings>
<add key="LDAPPath" value="LDAP://DC=MYSERVER,DC=COM" />
<add key="ADGroupName" value="Analyst"/>
</appSettings>
這是我的代碼
public class LdapAuthentication
{
private string _path;
private string _filterAttribute;
public LdapAuthentication()
{
_path = System.Configuration.ConfigurationManager.AppSettings["LDAPPath"].ToString();
}
public bool IsAuthenticated(string username, string pwd)
{
try
{
DirectoryEntry entry = new DirectoryEntry(_path, username, pwd);
entry.Path = _path;
entry.Username = username;
entry.Password = pwd;
// Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
// Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (string)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}
return true;
}
}
任何幫助,將不勝感激。 謝謝。
我有一個類似但更簡單的問題。 我成功使用了以下代碼:
private bool DoLogin(string userName, string password)
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DomainName.com")) {
bool isValid = pc.ValidateCredentials(userName, password);
if (isValid) {
// authenticated
...
return true;
}
else {
// invalid credentials
...
return false;
}
}
}
使用域名末尾的“.com”對於讓它為我工作非常重要。 沒有它我會得到你描述的相同症狀。
我剛剛在這里努力了幾個小時。 在網絡上沒有問題,通過VPN連接時出現很多問題。 看來,當您通過VPN連接時,DirectoryEntry的“連接字符串”必須更加精確。 我終於使用了這樣的LDAP地址/連接字符串:
LDAP://ip_of_primary_domain_controller/fully qualified path of the container object where the binding user is located
所以像這樣的東西對我有用:
DirectoryEntry directoryEntry = new DirectoryEntry(
"LDAP://192.168.0.20/OU=Service Accounts,OU=Admin Accounts,DC=myserver,DC=com",
"username@myserver.com", "password");
...其中“username@myserver.com”位於OU =服務帳戶,OU =管理員帳戶,DC = myserver,DC = com。 如果您使用SysInternals ADExplorer(或類似)來搜索您的用戶名,它將告訴您容器的正確完全限定路徑。
請參閱此處以獲取有關“連接字符串”中的確切內容的詳細答案: https : //serverfault.com/a/130556
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.