Azure Graph API多Web平台重定向URL异常:始终跳转至最后配置地址
解决Azure AD多重定向URL始终跳转最后一个的问题
问题根源
你当前的代码从配置文件中读取单个固定的RedirectUri,并全局设置到认证配置和挑战逻辑中。无论请求来自哪个托管域名,认证流程都会强制跳转到这个预先设定的URL,自然会覆盖Azure AD应用注册中配置的其他重定向地址。
解决方案:动态匹配请求来源的重定向URL
核心思路是不再硬编码固定的重定向地址,而是根据每个请求的实际来源动态生成对应的RedirectUri,同时让MSAL自动匹配Azure AD中已注册的重定向URL。
1. 修改Startup配置代码
移除全局固定的RedirectUri设置,让MSAL根据请求上下文自动处理:
public void Configuration(IAppBuilder app) { app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); var _Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); app.UseCookieAuthentication(new CookieAuthenticationOptions()); OwinTokenAcquirerFactory factory = TokenAcquirerFactory.GetDefaultInstance<OwinTokenAcquirerFactory>(); app.AddMicrosoftIdentityWebApp(factory); factory.Services .AddMicrosoftGraph() .AddInMemoryTokenCaches(); factory.Build(); }
2. 修改登录挑战逻辑,动态生成重定向URL
从当前请求上下文获取完整的请求路径,作为认证后的跳转地址:
// Sign in if (!Request.IsAuthenticated) { var context = HttpContext.GetOwinContext(); context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); // 动态获取当前请求的域名+回调路径 string currentRedirectUri = Request.Url.GetLeftPart(UriPartial.Path); context.Authentication.Challenge( new AuthenticationProperties { RedirectUri = currentRedirectUri }, OpenIdConnectAuthenticationDefaults.AuthenticationType); }
关键注意事项
- 确保Azure AD应用注册的Web平台下,已添加所有需要的重定向URL(格式示例:
https://app1.yourdomain.com/signin-oidc、https://app2.yourdomain.com/signin-oidc),路径需与你的认证回调路径一致(默认是/signin-oidc)。 - 若应用使用自定义回调路径,需保证每个重定向URL都包含正确路径,且代码中生成的
currentRedirectUri与之一一匹配。
内容的提问来源于stack exchange,提问作者Waqar Ali Saleemi
相关产品推荐
相关产品推荐

