c# - 给定用户名、密码和子域名,如何获取用户帐户的顶级域名?
问题描述
我正在编写一个在客户端机器上运行的程序( WinForms
, )。它从用户那里获取凭据(用户 ID、密码和子域名),并使用它们向程序远程连接的其他服务器进行身份验证(通过 )。其他服务器位于与客户端计算机所在域不同的域上。C#
Win 7
Active Directory
Win 7
使用NetworkCredential
、LdapDirectoryIdentifier
和LdapConnection
类,我可以测试不超过用户 ID、密码和子域名的凭据(请参阅 SO为什么 Active Directory 验证最后一个密码?)。
例如,对于用户帐户ssmith@xyz.gov
,我只需要提供ssmith
(user id)、密码ssmith
和xyz
(the 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
name,我如何获取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;
}
解决方案
成功绑定后,域的完整 DNS 名称将在LdapConnection
对象中:
var domain = connection.SessionOptions.DomainName;
在这种情况下,这将是“xyz.gov”。如果您只需要“gov”,那么您可以只取最后一个点之后的所有内容:
var tld = domain.Substring(domain.LastIndexOf('.') + 1);
推荐阅读
- javascript - 路由参数更改时刷新组件
- angular - 从子组件更新 ng-template
- ios - 如何在 Catalina 中访问“iTunes 共享”文件?
- aws-lambda - Skill Flow Builder Lambda 函数重置 DynamoDB
- iis - 您可以使用 URL_Rewrite rewritemaps 来修改 IIS 中的 ServerVariables 吗?
- python - 获取价值错误,不明白为什么
- r - dendextend:增加 groupLabels 中树状图节点的字体大小?
- html - 是否可以使用图标字体显示 TextSelection?
- python - 如何将此响应从字符串转换为字典?
- javascript - 如何在 Javascript 中检查数组中的多个值(避免使用过多的“或”语句)