Web.config authentication mode配置 .NET身份验证模式

6次阅读

windows身份验证需iis同步启用并禁用匿名认证,否则web.config中authentication mode=”windows”失效;asp.net core不读该配置;forms认证需放行登录页并避免手动重定向;mode=”none”表示交由外部验证。

Web.config authentication mode配置 .NET身份验证模式

authentication mode=”Windows” 什么时候会失效

Windows 身份验证不是开了就自动生效的——IIS 层必须同步启用 Windows 认证,且禁用匿名认证。否则 authentication mode="Windows"web.config 里写得再对也没用,请求直接绕过验证走匿名上下文。

  • IIS 管理器中对应站点 → “身份验证” → 确保 Windows 身份验证 已启用,匿名身份验证 已禁用
  • 若部署在 IIS express(如 VS 调试),需检查 .vsconfigapplicationhost.config 中对应 <location></location> 节点是否允许 Windows 认证
  • ASP.NET Core 项目不读 web.config<system.web><authentication></authentication></system.web>,该配置仅对 .NET Framework Web Forms / mvc 有效

Forms 认证跳转登录页却一直循环重定向

典型表现是访问受保护页面后反复跳到 loginUrl,甚至出现 302 套娃。根本原因通常是登录页本身也被 <authorization></authorization> 拦截,或表单提交路径未排除验证。

  • <forms loginurl="~/Account/Login" timeout="2880"></forms> 中的 loginUrl 对应页面必须在 <authorization></authorization> 中显式放行:
    <location path="Account/Login">   <system.web>     <authorization>       <allow users="*" />     </authorization>   </system.web> </location>
  • 登录逻辑里调用 FormsAuthentication.SetAuthCookie() 后,别手动 Response.Redirect() 到原页面——应交由 Forms 模块自动跳转,靠 ReturnUrl 参数驱动
  • 确保登录页的表单 action 指向一个无需认证的处理地址(如 Account/Login POST),而非直接写成 Account/SignIn 却没配 location 排除

mode=”None” 不代表没验证,只是关掉 ASP.NET 自带管道

authentication mode="None" 是最常被误解的选项:它不等于“没身份验证”,而是把验证责任完全交给外部(比如 IIS Basic、反向代理 JWT、或自定义 http 模块)。此时 HttpContext.User 仍可能有值,但来源与 <authentication></authentication> 配置无关。

  • 设为 None 后,FormsAuthentication 类所有方法(如 RedirectToLoginPage())将抛出 InvalidOperationException
  • 若你用 OWIN 或 IdentityServer,必须设 None,否则 ASP.NET 管道和中间件验证逻辑会冲突
  • 注意兼容性:.NET Framework 4.7.2+ 在 None 模式下仍会初始化部分安全上下文,某些老库(如旧版 Membership)可能意外触发空引用

Web.config 验证配置在子目录下被继承但可被覆盖

<system.web></system.web> 下的 <authentication></authentication> 默认向下继承,但子目录的 web.config 可用 <location></location> 或同级 <system.web></system.web> 重新声明——不过要注意语法限制。

  • 不能在子目录 web.config 中只写 <authentication mode="Forms"></authentication>,必须完整闭合:
    <system.web>   <authentication mode="Forms">     <forms loginUrl="~/Sub/Login" />   </authentication> </system.web>
  • <location path="api" inheritinchildapplications="false"></location><authentication></authentication> 无效——inheritInChildApplications 只作用于 <system.webserver></system.webserver> 和应用程序设置,身份验证配置始终继承
  • 若子应用是独立 AppDomain(如标记了 <applicationpath></applicationpath>),则父目录配置完全不生效,必须在子应用根目录配全

实际部署时最容易漏的是 IIS 层认证开关和子目录 location 授权的配套。这两处一错,web.config 里写得再准也白搭。

text=ZqhQzanResources