HttpContext.User.Identity 不使用 IIS Express 时未设置

HttpContext.User.Identity not set when not using IIS Express

我用 Visual Studio 2017 和 ASP.NET Core 1.2 做了一个玩具项目,当我的项目作为独立应用程序或在 IIS 10 中执行时,我在检索用户的 WindowsIdentity 时遇到了一些问题( WS2016),但可以与 IIS Express 一起正常工作。

我一直在使用同一个导航器,所以我相信它的配置是正确的。

我做了一个中间件:

public async Task Invoke(HttpContext context) {
    var identity = context.User.Identity;

    foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(identity)) {
        string name = descriptor.Name;
        object value = descriptor.GetValue(identity);
        _logger.LogDebug("{0}={1}", name, value);
        // Displays IsAuthenticated=False, Name=(null), ...
    }

    var contextIdentity = context.User.Identity as WindowsIdentity;
    // Here contextIdentity is null
    ...

我的 launchSettings.json 看起来像:

{
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:1028/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "AVVC.UI.ASP.SMP.Proto.Secur.API": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

在我的 .csproj 中,我为 web.config 添加了以下规则:

  <ItemGroup>
    <Content Update="web.config">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      <forwardWindowsAuthToken>True</forwardWindowsAuthToken>
    </Content>
  </ItemGroup>

并相应地生成web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath=".\blehbleh.exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true" />
  </system.webServer>
</configuration>

它不适用于独立应用程序,因为 launchSettings.json 文件中的 iisSettings 部分仅在 运行 来自 Visual Studio 的应用程序时使用。

This json file holds project specific settings associated with each debug profile, Visual Studio is configured to use to launch the application, including any environment variables that should be used.


要修复 IIS 10 的第二个问题,您需要为您的 IIS 站点设置 Windows 身份验证。来自 Configure Windows Authentication in ASP.NET Core 中的 "Customize Authentication" 部分:

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

也相关SO: