Windows ASP.NET 5 beta 8 中的身份验证支持

Windows Authentication support in ASP.NET 5 beta 8

我有一个 ASP.NET 5 MVC 6 Web API 项目。大多数 API 端点都具有 [Authorize] 属性,并且 Windows 在 IIS 和 Visual Studio 中的项目属性中都启用了身份验证。这在 beta 7 中一切正常。

但是,在 Beta 8 中,这不起作用。使用完全干净的项目很容易重现:

  1. 使用 ASP.NET 5 Web API 模板创建一个新项目。
  2. 获取项目(不是解决方案)的属性,转到调试选项卡,启用 Windows 身份验证并禁用匿名。保存更改。
  3. 按 F5 并让它尝试 运行 项目。

结果:

An error occurred attempting to determine the process id of the DNX process hosting your application.

  1. 现在返回项目属性并启用匿名。同时启用 Windows。保存更改。
  2. 转到您的控制器并添加 [Authorize] 属性。
  3. 再次F5。

结果:

这次项目启动了,但是web API returns 500。在输出中注意window:

Microsoft.AspNet.Mvc.Controllers.ControllerActionInvoker: Warning: Authorization failed for the request at filter 'Microsoft.AspNet.Mvc.Filters.AuthorizeFilter'.

该项目在发布到 IIS 时也不起作用。

如 Beta 8 中所述,announcement, the hosting model has changed such that IIS is now passing the request through to Kestrel. The Servers page 并未表明 Kestrel 支持 Windows 身份验证。是否有一些技巧可以让 Windows 身份验证在 beta 8 中工作?

有一个已知的工具错误会阻止您禁用 "anonymous authentication":https://github.com/aspnet/Hosting/issues/419

重新启用它,您看到的问题应该会消失。

确保您还在 Configure 方法的早期添加了 app.UseIISPlatformHandler();:需要它来解析与 IIS 流出的令牌相对应的 Windows 身份。

这似乎是 known bug in the Visual Studio debugging tooling when using IIS Express。在该问题得到解决之前,我发现的唯一解决方法是 运行 通过 WebListener 而不是 IIS Express 进行调试。要进行设置,请在 Startup.cs 中的 Configure 方法中添加:

// If we're self-hosting, enable integrated authentication (if we're using
// IIS, this will be done at the IIS configuration level).
var listener = app.ServerFeatures.Get<WebListener>();
if (listener != null)
{
    listener.AuthenticationManager.AuthenticationSchemes = 
        AuthenticationSchemes.NTLM;
}

然后在project.json添加一个weblistener cmd如下:

"commands": {
  "weblistener": "Microsoft.AspNet.Server.WebListener --config hosting.ini",
  "web": "Microsoft.AspNet.Server.Kestrel"
},

...或类似的。然后,如果您使用 weblistener 配置文件而不是 IIS Express(或 web,在 Kestrel 下不支持 NTLM)进行调试,您应该能够在解决 IIS Express 工具错误的同时继续工作。我相信,您需要将 Microsoft.AspNet.Server.WebListener 添加到 project.json 依赖项以启用 WebListener。

我发现,如果我直接在 project.json 中更改 "web" 命令,Visual Studio 会很有帮助地相当积极地将其更改回来,因此添加一个单独的命令 as recommended by the Microsoft team 似乎让一切快乐。

同样在 web.config 中你应该设置 forwardWindowsAuthToken="true" 例如:

 <httpPlatform processPath="%DNX_PATH%" arguments="%DNX_ARGS%" forwardWindowsAuthToken="true" startupTimeLimit="3600" />