[英]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.