首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >给定用户id、密码和子域名,如何获得用户帐户的顶级域名?

问给定用户id、密码和子域名,如何获得用户帐户的顶级域名?
EN

Stack Overflow用户
提问于 2018-05-03 15:31:02
回答 1查看 225关注 0票数 1

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

使用NetworkCredential、LdapDirectoryIdentifier和LdapConnection类,我可以使用用户id、密码和子域名测试凭据(请参阅S.O.为什么Active Directory要验证最后一个密码?的答案)。

例如,对于用户帐户ssmith@xyz.gov,我只需要提供ssmith (用户id)、ssmith的密码和xyz ( subdomain)。我不需要提供top-level domain name (在本例中是gov)。

现在,我想以编程的方式获得这个用户帐户的top-level domain name (在本例中是gov)。我研究了NetworkCredential、LdapDirectoryIdentifier和LdapConnection类的属性和方法。我查看了System.DirectoryServices.Protocols命名空间中的其他类。我看不到以编程方式获得top-level domain name的方法。

给定user id、password和subdomain名称,如何获得用户帐户的top-level domain name?

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

代码语言:javascript
复制
bool result = ValidateCredentials("ssmith","******", "xyz");

这是我的方法代码。

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-03 16:19:53

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

代码语言:javascript
复制
var domain = connection.SessionOptions.DomainName;

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

代码语言:javascript
复制
var tld = domain.Substring(domain.LastIndexOf('.') + 1);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50158813

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档