在 C# 中使用 vpn 进行活动目录身份验证
本文关键字:活动 身份验证 vpn | 更新日期: 2023-09-27 18:32:27
我正在开发一个Web应用程序,该应用程序根据Active Directory服务器对用户进行身份验证。现在,如果我从该 AD 服务器域下的开发 PC 运行我的代码,我的代码将顺利运行。我们需要使用 VPN 从完全不同的网络运行代码,而这里的开发 PC 不在该 AD 中。我在尝试访问AD服务器时遇到以下错误。
指定的域不存在或无法联系。
我的 VPN 工作正常。我可以使用此 VPN 访问远程桌面。我知道需要稍作调整才能解决问题,但找不到。我浏览了以下链接,但找不到任何解决方案。
-
通过 VPN 从 .NET 客户端进行域身份验证
-
如何在 Windows 窗体应用中获取 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