我有一些代码检查Active Directory
用户所属的所有组,这在我的开发环境中本地工作正常,但在我发布到Test系统时却没有。
同事建议可能在IIS
下运行应用程序池的帐户无法轮询Active Directory
。会是这种情况吗?什么可能导致没有团体被退回?
当我在本地运行我的代码时,我能够检索列表,但是测试结果为空。没有任何错误被抛出。
示例代码,我将“LIVE”更改为“TEST”,因为我们有一个多域网络,但都不起作用:
UserPrincipal user = UserPrincipal.Current;
if (user != null)
{
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "TEST");
List<Principal> groupResults = user.GetGroups(principalContext).ToList();
}
答案 0 :(得分:2)
似乎问题与您用来获取群组的用户有关。 UserPrincipal.Current获取其运行的线程的用户帐户。在IIS应用程序中,该帐户是应用程序的IIS应用程序池标识中指定的帐户。如果要查找特定用户帐户的Active Directory组以获取组,可以使用此代码(.Net 4):
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "TEST");)
{
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "A_User_Name");
foreach (var group in user.GetGroups())
{
Console.WriteLine(group.Name);
}
}
如果您想将此结果与特定域中的用户和群组进行比较,可以使用此工具:"Active Directory Users and Computers"
答案 1 :(得分:1)
如果它是ASP.NET,这应该有效:
public static List<string> GetGroups(string userName)
{
RoleProvider roleProvider = new WindowsTokenRoleProvider();
return roleProvider.GetRolesForUser(userName).ToList();
}
超级简单
答案 2 :(得分:1)
我不是百分百肯定,但我认为它比你的代码简单得多:
UserPrincipal user = UserPrincipal.Current;
if (user != null)
{
List<Principal> groupResults = user.GetGroups().ToList();
}