ASP.NET MVC 如何实现 Azure AD 与 Forms 混合身份认证
双认证共存的落地调整方案
1. 先把Web.config里的Forms配置改回来
之前你注释掉<authentication mode="Forms">这步直接把原有流程的根给拔了——这是System.Web MVC框架识别Forms认证Cookie、做未授权重定向的底层依据,注释完框架根本不会认你通过FormsAuthentication.SetAuthCookie写入的票据,当然怎么调都不好用。
直接把原来的配置恢复就行:
<authentication mode="Forms"> <forms loginUrl="~/Account/Index" timeout="2880" cookieless="UseDeviceProfile" name=".ASPXFORMSAUTH" /> </authentication>
2. 改OIDC中间件的运行模式,别让它乱拦请求
默认配置下OWIN的OpenIdConnect中间件是主动拦截模式(AuthenticationMode.Active),会把所有未授权请求的302重定向目标直接劫持到Azure AD登录页,根本不会走你配好的Forms登录逻辑。要改两个关键参数:
app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { // 你原来写的ClientId、Authority、RedirectUri这些配置全部保留 // 改成被动模式:只有你主动喊它启动流程,它才会跑,不会全局拦请求 AuthenticationMode = AuthenticationMode.Passive, Notifications = new OpenIdConnectAuthenticationNotifications { // 认证失败的时候别自动跳Azure AD,把控制权交回给Forms的重定向逻辑 AuthenticationFailed = context => { context.HandleResponse(); context.Response.Redirect($"/Account/Index?ReturnUrl={Uri.EscapeDataString(context.Request.Uri.PathAndQuery)}"); return Task.CompletedTask; }, // 登录成功的时候顺手把防伪令牌要的声明补上,解决报声明缺失的错 SecurityTokenValidated = context => { var identity = context.AuthenticationTicket.Identity; // 检查下缺啥补啥,防伪默认找这俩声明 if (!identity.HasClaim(c => c.Type == ClaimTypes.NameIdentifier)) { identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, identity.FindFirst(ClaimTypes.Name)?.Value ?? string.Empty)); } if (!identity.HasClaim(c => c.Type == "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider")) { identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "AzureAD")); } return Task.CompletedTask; } } });
改完之后,OIDC不会随便把走Forms登录的用户拽去AD页面了,只会在你点AD登录按钮、主动触发它的时候才会启动认证流程。
3. 调整AD登录按钮的触发逻辑
之前的自动跳转流程要改成手动触发挑战的模式:在AD登录对应的Action里,主动发起OIDC认证请求,让用户走AD的登录流程:
public ActionResult AzureAdLogin() { var properties = new AuthenticationProperties { RedirectUri = Url.Action("SignIn", "Account") }; HttpContext.GetOwinContext().Authentication.Challenge(properties, OpenIdConnectAuthenticationDefaults.AuthenticationType); return new HttpUnauthorizedResult(); }
4. 加个全局防伪配置兜底
在Global.asax的Application_Start方法里加一行配置,指定防伪令牌识别的唯一声明类型,避免后续再出同类的声明缺失报错:
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
几个容易踩的坑提个醒
- 改完配置一定要清掉浏览器里的旧Cookie,之前OIDC写的无效Cookie很容易导致重定向死循环
- 保证OIDC写的认证Cookie和Forms认证Cookie的Domain、路径配置一致,不然会出现换个路径就掉登录的问题
- 别额外引入OWIN的全局Cookie校验中间件,和System.Web内置的Forms认证逻辑会冲突,容易出莫名其妙的问题
内容的提问来源于stack exchange,提问作者Stephane Ehret
相关产品推荐
相关产品推荐

