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

Bha*_*dar 5 c# vpn active-directory

我正在开发一个Web应用程序,可以根据Active Directory服务器对用户进行身份验证。现在,如果我在该AD服务器所在的域中从开发PC运行我的代码,则我的代码可以平稳运行。我们需要使用VPN从完全不同的网络中运行代码,并且开发PC不在该AD中。尝试访问AD服务器时出现以下错误。

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

我的VPN运行正常。我可以使用此VPN访问远程桌面。我知道需要一些调整才能解决问题,但找不到它。我经过以下链接,但找不到任何解决方案。

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

  2. 如何在Windows窗体应用程序中获取VPN用户的当前用户身份?

以下是我在中的设置 web.config

<appSettings>
   <add key="LDAPPath" value="LDAP://DC=MYSERVER,DC=COM" />
   <add key="ADGroupName" value="Analyst"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)

这是我的代码

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激。谢谢。

Ste*_* S. 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在域名末尾使用“.com”对于让它为我工作非常重要。没有它我就会出现你所描述的相同症状。