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

Azure App Service启用HTTPS后,[Authorize]属性引发重定向异常

解决Azure App Service中ASP.NET MVC5启用HTTPS强制跳转后的重定向异常问题

我之前处理过好几起类似的案例,当ASP.NET MVC应用从纯HTTP切换到Azure强制HTTPS跳转后,和Azure AD的授权流程很容易出现重定向循环或者异常,核心问题大多和协议不一致、代理头识别、配置不匹配有关,给你梳理几个关键的解决方向:

1. 更新Azure AD应用注册的回复URL为HTTPS

Azure AD的授权流程对回调地址的协议严格匹配,你之前用HTTP时配置的http://mywebsite/admin/signin-oidc这类地址,现在必须全部替换成https://mywebsite/admin/signin-oidc(包括测试环境的对应地址)。如果这里没更新,Azure AD会拒绝回调请求,直接触发重定向异常。

2. 让MVC应用正确识别Azure的反向代理HTTPS头

Azure App Service的强制HTTPS是通过反向代理实现的,应用本身可能还认为当前请求是HTTP,导致重定向逻辑冲突。你可以在Global.asax.cs里添加逻辑处理X-Forwarded-Proto头:

protected void Application_BeginRequest()
{
    if (!Context.Request.IsSecureConnection && Context.Request.ServerVariables["HTTP_X_FORWARDED_PROTO"] == "https")
    {
        var uriBuilder = new UriBuilder(Context.Request.Url);
        uriBuilder.Scheme = Uri.UriSchemeHttps;
        uriBuilder.Port = 443;
        Response.Redirect(uriBuilder.Uri.ToString(), permanent: true);
    }
}

另外在Startup.Auth.cs的OIDC配置里,也要明确指定HTTPS的回调地址,同时在通知里修正授权请求的协议:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
    ClientId = "你的ClientId",
    Authority = "你的Authority地址",
    RedirectUri = "https://mywebsite/admin/signin-oidc",
    PostLogoutRedirectUri = "https://mywebsite/admin/signout-callback-oidc",
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        RedirectToIdentityProvider = n =>
        {
            // 确保授权请求的回调地址是HTTPS
            if (n.ProtocolMessage.RedirectUri.StartsWith("http://"))
            {
                n.ProtocolMessage.RedirectUri = n.ProtocolMessage.RedirectUri.Replace("http://", "https://");
            }
            return Task.FromResult(0);
        }
    }
});

3. 避免[RequireHttps]与Azure强制跳转的冲突

如果你的Admin控制器或Action用了默认的[RequireHttps]属性,它可能无法识别Azure的代理头,导致重复重定向。可以自定义一个适配代理的版本:

public class ProxyAwareRequireHttpsAttribute : System.Web.Mvc.RequireHttpsAttribute
{
    protected override void HandleNonHttpsRequest(AuthorizationContext filterContext)
    {
        // 识别Azure传递的HTTPS代理头,避免误判
        if (filterContext.HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_PROTO"] == "https")
        {
            return;
        }
        base.HandleNonHttpsRequest(filterContext);
    }
}

然后用这个自定义属性替换控制器上的默认[RequireHttps]。

4. 清理缓存确保配置生效

最后别忘了清除浏览器的缓存和Azure AD相关的认证Cookie,有时候旧的HTTP跳转规则会被缓存导致异常。同时可以重启Azure App Service实例,让新的HTTPS配置完全生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:25:28