【问题标题】:Active Directory PrincipalContext access denied when publishing to IIS发布到 IIS 时拒绝 Active Directory PrincipalContext 访问
【发布时间】:2020-03-10 14:16:50
【问题描述】:

我们有一个使用 Windows 身份验证的 .NET Core 2.2 Web Api。我们想创建一个页面,不同的管理员可以进入该页面并将用户添加/删除到特定的 AD 组。我们不能使用服务帐户或通用帐户,因为根据登录者的不同,他们将能够管理不同的组。

问题是,一旦我发布到 IIS,访问 AD 的就是 AppPools 身份,它被拒绝了。由于 .NET Core 不支持模拟,我如何以登录用户的身份向 LDAP 服务器发出请求?

public UserApiModel AddGroupMember(string networkId, string groupName)
{
    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DOMAIN"))
    {
        GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);
        var canAdd = true;
        var currentUsers = group.GetMembers();

        foreach (var groupUser in currentUsers)
        {
            if (groupUser.SamAccountName == networkId)
            {
                canAdd = false;
                break;
            }
        }

        if (canAdd)
        {
            var usr = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, networkId);

            if (usr != null)
            {
                group.Members.Add(pc, IdentityType.SamAccountName, "DOMAIN\\" + networkId);
                group.Save();

                return new UserApiModel
                    {
                        NetworkId = usr.SamAccountName,
                        Name = usr.DisplayName
                    };
            }
            else
                return null;
        }

        return null;
    }
}

【问题讨论】:

    标签: asp.net-core active-directory windows-authentication


    【解决方案1】:

    ASP.NET Core 不支持模拟,因为您无法像在 ASP.NET 中那样使用 web.config 设置使其在用户凭据下自动处理整个请求。

    但是,您仍然可以使用WindowsIdentity.RunImpersonated() 模拟特定代码块。 Windows 身份验证的文档中有一个Impersonation section,对此进行了描述。

    看起来像这样(在控制器中,HttpContext 可用):

    var userToImpersonate = (WindowsIdentity) HttpContext.User.Identity;
    
    WindowsIdentity.RunImpersonated(userToImpersonate.AccessToken, () =>
    {
        // Any code in here will run as the impersonated user
    });
    

    【讨论】:

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