【问题标题】:Winform user authorization via active directory通过活动目录 Winform 用户授权
【发布时间】:2011-01-13 05:27:00
【问题描述】:

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

using System.Security.Principal;
WindowsIdentity  identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole("someGroup");

上面的代码在我的域中的机器上运行良好,但是我确实有一些不在我的域中的机器,我在这些机器上安装了 WINFORM 应用程序。如何验证 AD 中的用户成员资格?

编辑——有没有办法提示windows登录?

【问题讨论】:

  • 你的意思是运行你的winform应用程序的用户(和你的机器)在另一个不受信任的域中还是根本不在域中? Windows登录是什么意思?您实际上可以编写自己的对话框来提示用户输入他的域用户和密码。然后,您使用他的域凭据与 Active Directory 对话。
  • 正确。有些机器不在域中。在哪里可以找到有关通过自定义登录框传递凭据的信息?我试过了,我可以进行身份​​验证,但无法获取会员信息。我关注了这个support.microsoft.com/kb/326340
  • 对我提出的答案有何评论?它对你有用吗?

标签: winforms active-directory .net-2.0


【解决方案1】:

由于您的计算机根本没有加入域,我们不能使用 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;
}

要使用此 IsInRole() 函数,您需要提供您的域名和域凭据。如果提供的用户名和密码错误,您将收到异常。

您需要 .NET 3.5 SP1 才能使用 AccountManagement API。另外,您可能想关注这个hotfix。如果在某些环境中运行,AccountManagement API 会出现一些错误。您可能需要应用此修补程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多