首页 > 解决方案 > 给定用户名、密码和子域名,如何获取用户帐户的顶级域名?

问题描述

我正在编写一个在客户端机器上运行的程序( WinForms, )。它从用户那里获取凭据(用户 ID、密码和子域名),并使用它们向程序远程连接的其他服务器进行身份验证(通过 )。其他服务器位于与客户端计算机所在域不同的域上。C#Win 7Active DirectoryWin 7

使用NetworkCredentialLdapDirectoryIdentifierLdapConnection类,我可以测试不超过用户 ID、密码和子域名的凭据(请参阅 SO为什么 Active Directory 验证最后一个密码?)。

例如,对于用户帐户ssmith@xyz.gov,我只需要提供ssmith(user id)、密码ssmithxyz(the subdomain)。我不需要提供top-level domain namegov在这种情况下)。

现在,我想以编程方式获取top-level domain name此用户帐户的 (gov在本例中)。我已经检查了 、 和 类的属性NetworkCredentialLdapDirectoryIdentifier方法LdapConnection。我查看了System.DirectoryServices.Protocols 命名空间中的其他类。我没有看到以编程方式获取top-level domain name.

给定user idpasswordsubdomainname,我如何获取top-level domain name用户帐户的 ?

这是我的代码。给定 ssmith@xyz.gov 的用户帐户,我的调用如下所示(星号代表 SecureString 密码)

bool result = ValidateCredentials("ssmith","******", "xyz");

这是我的方法代码。

private const int ERROR_LOGON_FAILURE = 0x31;

private bool ValidateCredentials(string username, SecureString ssPassword, string domain)
{

    //suports secure string 
    NetworkCredential credentials = new NetworkCredential(username, ssPassword, domain);

    LdapDirectoryIdentifier id = new LdapDirectoryIdentifier(domain);

    using (LdapConnection connection = new LdapConnection(id, credentials, AuthType.Kerberos))
    {
        connection.SessionOptions.Sealing = true;
        connection.SessionOptions.Signing = true;

        try
        {
            // The only way to test credentials on a LDAP connection seems to be to attempt a 
            // Bind operation, which will throw an exception if the credentials are bad
            connection.Bind();
        }
        catch (LdapException lEx)
        {
            credentials = null;
            id = null;

            if (ERROR_LOGON_FAILURE == lEx.ErrorCode)
            {
                return false;
            }

            throw;
        }
    }

    credentials = null;
    id = null;

    return true;
}

标签: c#winformsactive-directoryldapdomain-name

解决方案


成功绑定后,域的完整 DNS 名称将在LdapConnection对象中:

var domain = connection.SessionOptions.DomainName;

在这种情况下,这将是“xyz.gov”。如果您只需要“gov”,那么您可以只取最后一个点之后的所有内容:

var tld = domain.Substring(domain.LastIndexOf('.') + 1);

推荐阅读