用于检索所有用户的ASP.NET MVC Active Directory代码在部署到IIS 7时停止工作
本文关键字:代码 Directory 部署 停止工作 7时 IIS Active MVC 检索 用户 NET | 更新日期: 2023-09-27 17:59:30
我有一个intranet ASP.NET MVC3 web应用程序,该应用程序正在使用.NET Framework 4的Windows身份验证。我的所有代码都在对用户进行身份验证。我使用Windows身份验证进行基线身份验证,然后将Active Directory用户链接到SQL Server 2008中表中的用户,以获取特定于我的应用程序的其他用户属性。所有这些都很好。
在站点的某个部分,管理员可以选择要添加到SQL用户表中的Active Directory用户(请参阅上文),并输入其站点特定的属性(IsAdmin、ShoeSize等)。在这个屏幕上,我填充了一个下拉列表,用于从我创建的自定义对象中检索所有Active Directory,该对象仅包含Active Directory用户的用户名和全名属性。这是这个代码:
public IQueryable<ActiveDirectoryUser> ActiveDirectoryUsers
{
get
{
// get list of users in the Active Directory
DirectoryEntry dirEntry = new DirectoryEntry("WinNT://" + Environment.UserDomainName);
List<DirectoryEntry> activeDirectoryUsers = dirEntry.Children.Cast<DirectoryEntry>()
.Where(c => c.SchemaClassName == "User").ToList();
// populate a custom class I have to hold the active directory user's username and full name property values
return activeDirectoryUsers
.Where(u => !string.IsNullOrEmpty(u.Properties["FullName"].Value.ToString()))
.Select(u => new ActiveDirectoryUser()
{
NetworkId = String.Format(@"{0}'{1}", Environment.UserDomainName, u.Properties["Name"].Value),
FullName = u.Properties["FullName"].Value.ToString()
}).AsQueryable();
}
}
由于某些原因,当web应用程序部署到IIS 7时,此代码不会返回任何结果。但是,当在Visual Studio中从IIS学习版运行网站时,这种方法非常有效。你知道为什么会发生这种事吗?我一直在寻找IIS设置作为罪魁祸首,但没有发现任何有用的东西。我需要更改检索Active Directory用户的方式吗?非常感谢。
这个问题最终是Eric J.答案和我获取Active Directory条目的代码更改的结合。我发现DirectoryEntry方法可以重载,以获取用于权限的用户名和密码(例如,您不必依赖IIS运行的任何帐户。以下是代码:
List<SearchResult> searchResults;
// use login account to access active directory (otherwise it will use the IIS user account, which does not have permissions)
using (DirectoryEntry root = new DirectoryEntry("LDAP://CN=Users,DC=test,DC=example,DC=com", "usernameCredential", "passwordCredential"))
using (DirectorySearcher searcher = new DirectorySearcher(root, "(&(objectCategory=person)(objectClass=user))"))
using (SearchResultCollection results = searcher.FindAll())
{
searchResults = results.Cast<SearchResult>().ToList();
}
// get the active directory users name and username
return searchResults
.Select(u => new ActiveDirectoryUser()
{
NetworkId = String.Format(@"{0}'{1}", this._domainName, u.Properties["sAMAccountName"][0]),
FullName = (string) u.Properties["cn"][0]
}).AsQueryable();
这允许我获取Active Directory条目,但只有那些是用户和个人对象。然后我使用LINQ将其映射到我的自定义模型。
在Visual Studio下的IIS学习版中运行时,您拥有的权限集比在IIS 7的默认安全上下文中运行的权限集高得多。
您必须准确了解以这种方式查询Active Directory需要哪些权限,并确保您的应用程序在IIS 7下运行的应用程序池具有该权限。请小心仅授予此操作所需的权限,并确保在继续操作之前仔细查看授予这些权限的含义。