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

如何配置仅注册的Azure B2C用户流策略?调用报HTTP 401错误如何解决

排查与修复方案

  • 1、给SignUp方法添加[AllowAnonymous]特性
    如果你的AccountController没有全局加[AllowAnonymous],或者站点全局配置了身份验证拦截规则,未登录状态下访问SignUp方法会直接被ASP.NET管道拦截返回401,不会执行你写的Challenge逻辑。修改后的方法示例如下:
[AllowAnonymous]
public void SignUp()
{
    // 先将策略存入Owin上下文供中间件读取
    HttpContext.GetOwinContext().Set("Policy", Globals.SignUpPolicyId);
    HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, Globals.SignUpPolicyId);
}
  • 2、检查Startup.Auth.cs中的OpenIdConnect中间件配置,是否添加了多策略处理逻辑
    默认配置仅支持默认的SignUpSignIn策略,单独调用其他用户流策略时需要在RedirectToIdentityProvider通知中动态替换授权地址的策略参数,示例配置如下:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
    ClientId = Globals.ClientId,
    Authority = $"https://{Globals.TenantName}.b2clogin.com/{Globals.TenantName}.onmicrosoft.com/{Globals.SignUpSignInPolicyId}/v2.0/",
    RedirectUri = Globals.RedirectUri,
    PostLogoutRedirectUri = Globals.RedirectUri,
    ResponseType = "id_token",
    Scope = "openid profile",
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        RedirectToIdentityProvider = n =>
        {
            // 读取上下文中存入的自定义策略,替换默认策略
            var customPolicy = n.OwinContext.Get<string>("Policy");
            if (!string.IsNullOrEmpty(customPolicy))
            {
                n.ProtocolMessage.IssuerAddress = n.ProtocolMessage.IssuerAddress.Replace(Globals.SignUpSignInPolicyId, customPolicy);
            }
            return Task.CompletedTask;
        }
    }
});
  • 3、确认Azure AD B2C应用注册的重定向URI配置正确
    你使用的OWIN中间件默认回调路径为/signin-oidc,需要在Azure门户的应用注册中添加对应环境的回调地址,比如本地调试时要加http://localhost:1111/signin-oidc,否则身份验证完成后回调会被拦截返回401。

  • 4、核对Globals.SignUpPolicyId的取值是否和Azure门户中用户流的ID完全一致,避免大小写错误、多余空格等低级问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:36:02