You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Web应用微软登录自定义重定向URL不生效问题

问题原因与解决方案

你混淆了两个关键概念,导致自定义重定向URL未生效:

  1. 发给Azure AD的redirect_uri:这个地址是Azure AD完成认证后回调到你应用的路径,由AddMicrosoftAccount配置中的CallbackPath决定,默认值是/signin-microsoft,这就是你看到请求里始终用这个地址的原因。
  2. AuthenticationProperties.RedirectUri:这是Azure AD回调到你应用后,本地内部跳转的最终页面,不是发给Azure AD的回调地址。

解决步骤

1. 修改微软认证配置,指定CallbackPath

在startup.cs的AddMicrosoftAccount配置中,添加CallbackPath,值要和你在Azure AD里配置的重定向URL路径一致:

services.AddAuthentication("Cookies")
    .AddCookie(opt =>
    {
        opt.Cookie.Name = "AuthCookie";
    })
    .AddMicrosoftAccount(opt => {
        opt.SignInScheme = "Cookies";
        opt.AuthorizationEndpoint = _configuration["AzureAd:AuthorizationEndpoint"];
        opt.TokenEndpoint = _configuration["AzureAd:TokenEndpoint"];
        opt.ClientId = _configuration["AzureAd:ClientId"];
        opt.ClientSecret = _configuration["AzureAd:ClientSecret"];
        // 新增:指定回调路径,与Azure AD配置的重定向URL路径匹配
        opt.CallbackPath = "/Profile";
    });

2. 确保Azure AD重定向URL配置正确

在Azure AD应用注册中,重定向URL必须包含完整的域名+路径,比如本地开发环境要配置:
https://localhost:5000/Profile
生产环境则替换为你的实际域名,比如https://your-app-domain.com/Profile

3. 调整登录逻辑(可选)

如果你希望Azure AD回调完成后,再跳转到其他页面(而非停在/Profile),可以保留AuthenticationProperties.RedirectUri的设置:

[HttpGet("microsoft")]
public async Task<ActionResult> Login(string RedirectUri)
{
    AuthenticationProperties props = new AuthenticationProperties
    {
        // 这里设置的是认证完成后本地跳转的目标页面
        RedirectUri = RedirectUri ?? "/Profile"
    };
    return Challenge(props, MicrosoftAccountDefaults.AuthenticationScheme);
}

关键说明

  • 微软认证中间件会自动拦截CallbackPath对应的请求,完成令牌验证、登录流程,之后再跳转到RedirectUri指定的页面。
  • 必须保证Azure AD中的重定向URL与CallbackPath的完整URL完全匹配,否则会触发Azure AD的回调错误。

内容的提问来源于stack exchange,提问作者Padrophil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 16:25:24