ASP.NET MVC应用中AAD认证页面重定向异常问题
ASP.NET MVC应用AAD认证重定向异常问题
问题现象
运行应用访问受认证保护的路由时,未自动重定向至AAD认证页面,停留在原页面,无任何重定向操作或错误提示。
现有配置概述
- 已将应用配置为使用AAD身份认证
- Azure门户中已设置匹配的重定向URI:
https://localhost:44341/signin-oidc、https://localhost:44387/signin-oidc、https://localhost:44320/signin-oidc - 使用
Microsoft.Owin.Security和Microsoft.Owin.Security.OpenIdConnect作为认证中间件
相关代码片段
Startup.Auth.cs
public partial class Startup { private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; private static string aadInstance = EnsureTrailingSlash(ConfigurationManager.AppSettings["ida:AADInstance"]); private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"]; private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"]; private static string authority = aadInstance + tenantId + "/v2.0"; public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = authority, PostLogoutRedirectUri = postLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications() { SecurityTokenValidated = (context) => { string name = context.AuthenticationTicket.Identity.FindFirst("preferred_username").Value; context.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Name, name, string.Empty)); return System.Threading.Tasks.Task.FromResult(0); } } }); } private static string EnsureTrailingSlash(string value) { if (value == null) { value = string.Empty; } if (!value.EndsWith("/", StringComparison.Ordinal)) { return value + "/"; } return value; } }
Startup.cs
namespace OidcTestDemo { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } }
Web.config
<appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <add key="ida:ClientId" value="" /> <add key="ida:AADInstance" value="https://login.microsoftonline.com/" /> <add key="ida:Domain" value="" /> <add key="ida:TenantId" value="" /> <add key="ida:PostLogoutRedirectUri" value="https://localhost:44341/signin-oidc" /> </appSettings>
AccountController.cs
namespace OidcTestDemo.Controllers { public class AccountController : Controller { public void SignIn() { if (!Request.IsAuthenticated) { HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType); } } public void SignOut() { string callbackUrl = Url.Action("SignOutCallback", "Account", routeValues: null, protocol: Request.Url.Scheme); HttpContext.GetOwinContext().Authentication.SignOut( new AuthenticationProperties { RedirectUri = callbackUrl }, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); } public ActionResult SignOutCallback() { if (Request.IsAuthenticated) { // Redirect to home page if the user is authenticated. return RedirectToAction("Index", "Home"); } return View(); } } }
排查与解决步骤
- 补全配置必填项:Web.config中的
ida:ClientId、ida:TenantId为空,必须填入Azure门户应用注册对应的Client ID和租户ID,否则认证中间件无法正常初始化。 - 确认路由保护:检查受保护的Controller/Action是否添加了
[Authorize]特性,未添加则不会触发认证重定向逻辑。 - 启用自动挑战模式:在
OpenIdConnectAuthenticationOptions中添加AuthenticationMode = AuthenticationMode.Active,并补充RedirectToIdentityProvider通知确保未认证时触发重定向:Notifications = new OpenIdConnectAuthenticationNotifications() { SecurityTokenValidated = (context) => { string name = context.AuthenticationTicket.Identity.FindFirst("preferred_username").Value; context.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Name, name, string.Empty)); return System.Threading.Tasks.Task.FromResult(0); }, RedirectToIdentityProvider = (context) => { if (!context.OwinContext.Authentication.User.Identity.IsAuthenticated && context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication) { context.ProtocolMessage.RedirectUri = postLogoutRedirectUri; } return Task.FromResult(0); } } - 验证登录触发逻辑:确保受保护页面的登录入口指向
Account/SignIn,或在全局过滤器中配置未认证时自动跳转至该动作。 - 检查HTTPS环境:AAD认证要求回调地址必须为HTTPS,确认本地调试的IIS Express HTTPS端口配置与Azure门户的重定向URI一致。
- 启用日志排查:在Web.config中添加Owin日志配置,捕获认证过程中的异常信息:
<system.diagnostics> <sources> <source name="Microsoft.Owin" switchValue="Verbose"> <listeners> <add name="OwinListener" /> </listeners> </source> </sources> <sharedListeners> <add name="OwinListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="owin.log" /> </sharedListeners> <trace autoflush="true" /> </system.diagnostics>
内容的提问来源于stack exchange,提问作者Shrutika Jaiswal
相关产品推荐
相关产品推荐

