由于您的计算机根本没有加入域,因此我们无法使用 WindowsIdentity 或 WindowsPrincipal 然后检查其 IsInRole() 方法。仅当您的计算机加入域并且它使用您的域计算机帐户执行 S4USelf 时,IsInRole() 方法才有效。
您也不能使用 LogonUser 方法,因为您的计算机不允许您从不受信任的林创建登录会话。
我想我们只能直接查询Active Directory来获取我们想要的信息。据我所知,您发布的 Microsoft 知识库中的代码运行得不太好。它正在尝试从 memberOf 属性进行查询。组信息并不总是可以从 memberOf 属性中获得。
我刚刚使用 AccountManagement 编写了一个 IsInRole() 函数。我想这就是你想要的。 IsInRole() 函数将调用递归函数 IsInGroup() 来找出用户所属的所有组。
private bool IsInRole(string domain, string username, string password, string role)
{
using (var context = new PrincipalContext(ContextType.Domain, domain, username, password))
{
GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, role);
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
return IsInGroup(user, group);
}
}
private bool IsInGroup(Principal principal, GroupPrincipal group )
{
if (principal.IsMemberOf(group))
return true;
foreach (var g in principal.GetGroups())
{
if (IsInGroup(g, group))
return true;
}
return false;
}
要使用此 IsInRole() 函数,您需要提供您的域名和域凭据。如果提供的用户名和密码错误,您将收到异常。
您需要 .NET 3.5 SP1 才能使用 AccountManagement API。另外,您可能还想关注这个hotfix http://support.microsoft.com/kb/969166。如果在某些环境中运行,AccountManagement API 会出现一些错误。您可能需要应用修补程序。