Winforms 通过active directory进行Winform用户授权

Winforms 通过active directory进行Winform用户授权,winforms,active-directory,.net-2.0,Winforms,Active Directory,.net 2.0,在我的应用程序中执行任务之前,我使用以下代码验证AD中的用户成员身份 using System.Security.Principal; WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole("someGroup"); 上面的代码适用于我所在域中的计算机,但是我确

在我的应用程序中执行任务之前,我使用以下代码验证AD中的用户成员身份

using System.Security.Principal;
WindowsIdentity  identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole("someGroup");
上面的代码适用于我所在域中的计算机,但是我确实有一些不在我所在域中的计算机安装了WINFORM应用程序。如何验证AD中的用户成员资格


编辑-是否有方法提示windows登录?

由于您的计算机根本没有加入域,我们无法使用WindowsIdentity或WindowsPrincipal,然后检查其IsInRole()方法。IsInRole()方法仅在您的计算机已加入域并且正在使用域计算机帐户执行S4USelf时才有效

您也不能使用LogonUser方法,因为您的计算机不允许您从不受信任的林创建登录会话

我想我们只能直接查询Active Directory来获得我们想要的信息。据我所知,您发布的Microsoft知识库中的代码工作得不太好。它正在尝试从memberOf属性查询。组信息并非总是可以从属性的memberOf获得

我刚刚使用AccountManagement编写了一个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()函数,您需要提供域名和域凭据。如果提供的用户名和密码错误,则会出现异常


您需要.NET3.5SP1才能使用AccountManagementAPI。另外,您可能会注意这一点。AccountManagement API在某些环境中运行时会出现一些错误。您可能需要应用修补程序。

您的意思是运行winform应用程序的用户(和您的计算机)在另一个不受信任的域中,还是根本不在域中?你说的Windows登录是什么意思?实际上,您可以编写自己的对话框来提示用户输入其域用户和密码。然后,您使用他的域凭据与Active Directory.Correct对话。某些计算机不在域上。在哪里可以找到有关通过自定义登录框传递凭据的信息?我试过了,我可以认证但不能获得会员信息。我遵循了这一点,对我提出的答案有何评论?对你有用吗?