Sai*_*han 7 active-directory .net-2.0 winforms
我有一种情况,我在我的应用程序中执行任务之前使用以下代码来验证AD中的用户成员资格
using System.Security.Principal;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole("someGroup");
Run Code Online (Sandbox Code Playgroud)
上面的代码适用于我的域上的计算机,但是我确实有一些机器不在我的域上,我安装了WINFORM应用程序.如何验证AD中的用户成员身份?
编辑 - 有没有办法提示Windows登录?
由于您的计算机根本没有加入域,我们无法使用WindowsIdentity或WindowsPrincipal,然后检查其IsInRole()方法.IsInRole()方法仅在您的计算机加入域并且使用您的域计算机帐户执行S4USelf时才有效.
您也不能使用LogonUser方法,因为您的计算机不允许您从不受信任的林创建登录会话.
我想我们只能直接查询Active Directory以获取我们想要的信息.据我所知,您发布的Microsoft KB中的代码不能很好地工作.它试图从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;
}
Run Code Online (Sandbox Code Playgroud)
要使用此IsInRole()函数,您需要提供域名和域凭据.如果提供的用户名和密码错误,您将收到异常.
您需要.NET 3.5 SP1才能使用AccountManagement API.另外,您可能希望关注此修补程序.如果在某些环境中运行,AccountManagement API会出现一些错误.您可能需要应用此修补程序.
| 归档时间: |
|
| 查看次数: |
11839 次 |
| 最近记录: |