使用C#在VPN中进行Active Directory身份验证

5
我正在开发一个网页应用程序,可以对用户进行Active Directory服务器的身份验证。如果我在该AD服务器所在的域下从开发PC运行我的代码,我的代码将正常运行。现在我们需要使用VPN从完全不同的网络运行代码,并且这里的开发PC没有加入AD。在尝试访问AD服务器时,我遇到了以下错误:

指定的域不存在或无法联系。

我的VPN运行良好,我可以使用此VPN访问远程桌面。我知道解决问题需要进行一些小调整,但找不到方法。我查看了以下链接,但没有找到任何解决方案:

  1. .NET客户端通过VPN进行域身份验证

  2. 如何为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;
    }
}

任何帮助都将不胜感激。谢谢。
2个回答

0

我刚刚花了几个小时来解决这个问题。在网络上没有问题,但是通过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


0

我有一个类似但更简单的问题。我成功地使用了以下代码:

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”对我很重要,这样才能让它正常工作。如果没有它,我会遇到你描述的相同症状。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接