Asp.net core 发布到IIS时拒绝Active Directory PrincipalContext访问

Asp.net core 发布到IIS时拒绝Active Directory PrincipalContext访问,asp.net-core,active-directory,windows-authentication,Asp.net Core,Active Directory,Windows Authentication,我们有一个使用Windows身份验证的.NETCore2.2WebAPI。我们希望创建一个页面,不同的管理员可以进入该页面,并将用户添加/删除到特定的广告组。我们不能使用服务帐户或通用帐户,因为根据登录用户的不同,他们将能够管理不同的组 问题是,一旦我发布到IIS,访问AD的是AppPools标识,它被拒绝。既然.NET Core不支持模拟,我如何以登录用户的身份向LDAP服务器发出请求 public UserApiModel AddGroupMember(string networkId, s

我们有一个使用Windows身份验证的.NETCore2.2WebAPI。我们希望创建一个页面,不同的管理员可以进入该页面,并将用户添加/删除到特定的广告组。我们不能使用服务帐户或通用帐户,因为根据登录用户的不同,他们将能够管理不同的组

问题是,一旦我发布到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不支持模拟,因为您无法让它像在ASP.NET中那样使用web.config设置自动处理用户凭据下的整个请求

但是,您仍然可以使用模拟特定代码块。有关Windows身份验证的文档中有一个详细说明,其中描述了这一点

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

var userToImpersonate=(WindowsIdentity)HttpContext.User.Identity;
WindowsIdentity.RunImpersonated(userToImpersonate.AccessToken,()=>
{
//这里的任何代码都将作为模拟用户运行
});