如何仅为ASP.NET Core的子路径配置Windows身份验证
解决方案
第一步:修正web.config配置
你之前的报错和全局弹框问题根源是IIS层面的认证配置范围不对,需要先把全局认证设为允许匿名、关闭Windows认证,仅给目标路径单独开启Windows认证,配置示例如下:
<?xml version="1.0" encoding="utf-8"?> <configuration> <!-- 全局路由默认配置:开启匿名,关闭Windows认证,避免所有请求触发校验 --> <system.webServer> <security> <authentication> <anonymousAuthentication enabled="true" /> <windowsAuthentication enabled="false" /> </authentication> </security> </system.webServer> <!-- 仅针对/testendpoint路径:关闭匿名,开启Windows认证 --> <location path="testendpoint" inheritInChildApplications="false"> <system.webServer> <security> <authentication> <anonymousAuthentication enabled="false" /> <windowsAuthentication enabled="true" /> </authentication> </security> </system.webServer> </location> </configuration>
如果修改后出现500.19错误,需要打开IIS管理器的对应站点「身份验证」功能,将匿名身份验证、Windows身份验证都设为已启用,允许web.config覆写相关配置。
第二步:调整应用认证服务注册
保留你原有项目的认证配置,仅追加Negotiate(Windows认证)方案即可,不需要修改默认认证方案,示例如下:
using Microsoft.AspNetCore.Authentication.Negotiate; using Microsoft.AspNetCore.Authentication.Cookies; // 假设原有默认认证方案为Cookie,保留原有配置,仅追加AddNegotiate() services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { // 原有Cookie认证的配置逻辑 }) .AddNegotiate();
第三步:给目标接口指定认证方案
在/testendpoint对应的Controller或Action上,显式指定使用Negotiate认证方案即可:
using Microsoft.AspNetCore.Authentication.Negotiate; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; public class TestController : Controller { [HttpGet] [Route("testendpoint")] [Authorize(AuthenticationSchemes = NegotiateDefaults.AuthenticationScheme)] public IActionResult TestEndpoint() { // 可通过User.Identity获取当前Windows认证的用户信息 return Ok($"认证用户:{User.Identity?.Name}"); } // 其余接口走原有默认认证逻辑,不受影响 [HttpGet] [Route("other")] public IActionResult Other() { return Ok("走原有认证逻辑"); } }
原问题根因说明
- 报错
The Negotiate Authentication handler cannot be used on a server that directly supports Windows Authentication是因为IIS全局开启了Windows认证,Negotiate中间件检测到服务器层已原生支持Windows认证,触发冲突。 - 之前修改location path后根路径报错,是因为全局没有显式关闭Windows认证,中间件依然检测到服务器层的Windows认证配置导致冲突。
内容的提问来源于stack exchange,提问作者Poul K. Sørensen
相关产品推荐
相关产品推荐

