我需要为我的intranet web应用程序创建一个方法,该方法将根据默认域或用户指定的域,使用DirectoryServices对用户进行身份验证。
在我的登录表单中,用户既可以以"username"和"password的形式提供凭证,也可以在用户与when服务器位于同一个域中时使用"domain\username"和"password"。
string domain = "";
// Code to check if the username is in form of "domain\user" or "user"
string username = ParseUsername(username, out domain);
if(domain == "")
domain = defaultDomain;
PrincipalContext context = new PrincipalContext(ContextType.Domain, domain, username, password);
bool IsAuthenticated = context.ValidateCredentials(username, password)我将用户名和密码传递给PrincipalContext构造函数,以便在尝试访问另一个域的情况下绑定调用。
对于本地域,代码工作正常。但是,当我试图检查另一个通过用户名指定的域时,我会得到一个“无法联系服务器”错误。
我也尝试使用不同的ContextOptions,如ContextOptions.SimpleBind或ContextOptions.Negotiate,但我似乎总是得到相同的结果。
我需要实现这一点,因为应用程序是通过单个域或多个域环境向不同的客户提供的。在“远程”域的情况下,还有什么需要我指定的吗?代码需要灵活,因为这将部署在不同的环境中。
谢谢
编辑:我必须指出,为了利用它提供的其他功能,我更愿意使用DirectoryServices.AccountManagement和PrincipalContext进行编辑。
另外,我必须指出,对于我的测试,我的Dev机器位于10.0.0.*网络上,而我测试的第二个域是在10.0.1.*上。我有一个路由,而且我可以成功地使用ldap客户机连接,所以问题是为什么我不能通过我的asp.net应用程序连接域。
发布于 2012-02-23 10:48:20
我已经想出了这个问题的解决办法。
为了支持多个域,无论是在信任关系中还是在孤立的网络中,首先我在web.config中添加了一个web.config来列出域及其域控制器。
<domains>
<add key="domain1" value="10.0.0.1"/>
<add key="domain2" value="10.0.1.11"/>
</domains>(关于this so question中的配置添加的更多信息)
然后,下一步是以我在问题中提到的方式从用户的凭据中读取域。得到域后,我尝试从配置值中查找相应的域控制器,以获得适当的LDAP连接字符串。所以我的方法是:
private string GetLDAPConnection(string a_Domain, string a_Username, string a_Password)
{
// Get the domain controller server for the specified domain
NameValueCollection domains = (NameValueCollection)ConfigurationManager.GetSection("domains");
string domainController = domains[a_Domain.ToLower()];
string ldapConn = string.Format("LDAP://{0}/rootDSE", domainController);
DirectoryEntry root = new DirectoryEntry(ldapConn, a_Username, a_Password);
string serverName = root.Properties["defaultNamingContext"].Value.ToString();
return string.Format("LDAP://{0}/{1}", domainController, serverName);
}返回正确的连接字符串后,通过寻址适当的LDAP,进行新的调用,以验证用户的身份。
...
string ldapConn = GetLDAPConnection(domain, username, a_Password);
DirectoryEntry entry = new DirectoryEntry(ldapConn, username, a_Password);
try
{
try
{
object obj = entry.NativeObject;
}
catch(DirectoryServicesCOMException comExc)
{
LogException(comExc);
return false;
}
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = string.Format("(SAMAccountName={0})", username);
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();从这一点开始,我还可以执行我想要的所有其他查询,例如用户的组成员身份等。
由于对远程域的调用需要绑定到用户,所以我使用“调用”用户凭据。通过这种方式,用户将得到身份验证,并将调用绑定到特定用户。此外,我还指定了一个“默认”域,用于用户提供凭据而不指定域的情况。
然而,我并没有像我所希望的那样使用PrincipalContext,但从好的方面说,这个解决方案也适用于较老的.NET 2.0应用程序。
我不知道这是否是解决这个问题的最佳办法,但它似乎适用于我们迄今所进行的测试。
发布于 2012-02-20 14:37:38
我不知道为什么我被否决了,但我认为可能是错误的,您代码所在的服务器/域与您试图联系的域之间的信任级别可能无法建立。我不能告诉你为什么会发生这种事。
[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]您可以尝试将其添加到您的函数之上,看看它是否帮助您通过,但除此之外,我不知道为什么在WinNT域上搜索所有可能的用户是错误的。希望这能有所帮助
https://stackoverflow.com/questions/9362724
复制相似问题