Windows 在 iis 上部署后身份验证不起作用

Windows authentication doesn't work after deploy on iis

我对这段简单的代码有疑问:

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        ClaimsPrincipal user = _httpContextAccessor.HttpContext.User;
        ClaimsIdentity identity = user.Identity as ClaimsIdentity;
        string userName = identity.Name;  //!!!

        _logger.Trace("windows user `{0}` is trying to access the system", userName);
        var admins = _configurationRoot.GetSection(ConfigDescription.Admins).Get<List<string>>();
        if (!admins.Contains(userName)) 
        {
            _logger.Trace("Permission denied.");
            context.Result = new RedirectResult("/error/unauthorized", false);
        }
    }

当我在 Visual Studio 中通过 IIS Express 启动我的 asp net 应用程序时,一切正常。我在这种情况下的日志:

2021-12-25 22:02:53.1783 TRACE     windows user `Domain\username` is trying to access the system.

但是在远程 IIS 上发布后 userName 总是空的。

2021-12-25 19:11:55.2524 TRACE     windows user `` is trying to access the system.
2021-12-25 19:11:55.2524 TRACE     Permission denied.

我尝试从本地主机和通过域名打开网站,还将其添加到受信任的站点,但没有任何帮助。

web.config :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" forwardWindowsAuthToken="true" arguments=".\BlaBla.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

在 IIS 上启用了匿名身份验证

因为如果没有,我连 error/unauthorized 这样的页面都打不开:

要在 IIS 中启用 windows 身份验证,需要确保以下内容

  1. 在 IIS 中启用 Windows 身份验证
  2. 在 IIS Web 应用程序中启用 Windows 身份验证

1.在 IIS 中启用 Windows 身份验证

我们需要在“Windows 功能”中启用 Windows 身份验证(运行 命令:optionalfeatures。Win + R → optionalfeatures)

2。在 IIS Web 应用程序中启用 Windows 身份验证

然后我们需要为应用程序启用windows 身份验证。可以在 web.config 中完成,如下所示或在 IIS

中完成

web.config

<system.webServer>
        <security>
            <authentication>
                <windowsAuthentication enabled="true" />
                <anonymousAuthentication enabled="false" />
            </authentication>
        </security>
    </system.webServer>

IIS

Select 左侧节点中的应用程序和 select 功能视图中的“身份验证”

启用 Windows 身份验证并禁用匿名身份验证。

更多信息

  1. IIS Windows Authentication
  2. Windows Authentication in ASP.NET Core