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

Azure AD B2C登出异常:从B2B迁移后原登出方法失效

Azure AD B2C 登出异常问题处理

将系统从Azure AD B2B迁移至Azure AD B2C后,原有的登出代码失效,尝试新方案后仍存在问题:执行登出操作后,再次登录会自动复用之前的会话数据,无法完全退出账号。

原有登出代码(已失效)

public IActionResult SignOut()
{
    var callbackUrl = Url.Action("Index", "Inicio", values: null, protocol: Request.Scheme);
    return SignOut(
        new AuthenticationProperties { RedirectUri = callbackUrl },
        CookieAuthenticationDefaults.AuthenticationScheme,
        OpenIdConnectDefaults.AuthenticationScheme);
}

尝试的新登出方案(仍存在问题)

[HttpGet]
[AllowAnonymous]
public IActionResult SignOut()
{
    return RedirectToAction("Logout");
}

[HttpGet]
public async Task<IActionResult> Logout()
{
    HttpContext.Session.Clear();
    await HttpContext.SignOutAsync(AzureADB2CDefaults.AuthenticationScheme);
    await HttpContext.SignOutAsync(AzureADB2CDefaults.CookieScheme);
    await HttpContext.SignOutAsync(AzureADB2CDefaults.OpenIdScheme);
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

    var config = InfoUserAD.ReadConfig();

    string tenantId = config.Domain.Split('.')[0];
    string policy = config.Resource;
    string clientId = config.ClientId;
    string redirectUrl = "http://localhost:5001/"; // 登出后重定向的URL
    string logoutUrl = $"https://{tenantId}.b2clogin.com/{tenantId}.onmicrosoft.com/oauth2/v2.0/logout?p={policy}";

    string encodedRedirectUrl = HttpUtility.UrlEncode(redirectUrl);
    string logoutFullUrl = $"{logoutUrl}&post_logout_redirect_uri={encodedRedirectUrl}";

    return Redirect(logoutFullUrl); 
}

问题原因与修正方案

核心问题

手动拼接登出URL的方式没有正确触发Azure AD B2C的全局会话终结,仅清理了应用本地的Cookie和会话,B2C端的SSO会话仍保留,导致再次登录时自动复用原有身份信息。

正确实现方式

利用OpenID Connect中间件自动处理B2C登出流程,确保同时终结本地会话与B2C全局会话:

[HttpGet]
public async Task<IActionResult> SignOut()
{
    // 构建登出后的重定向URL
    var callbackUrl = Url.Action("Index", "Inicio", values: null, protocol: Request.Scheme);
    
    var authProperties = new AuthenticationProperties
    {
        RedirectUri = callbackUrl
    };

    // 依次登出本地Cookie会话与B2C OpenID会话
    await HttpContext.SignOutAsync(AzureADB2CDefaults.CookieScheme, authProperties);
    await HttpContext.SignOutAsync(AzureADB2CDefaults.OpenIdScheme, authProperties);

    return new EmptyResult();
}

关键注意事项

  1. 配置登出重定向URL:必须在Azure AD B2C的应用注册中,将上述callbackUrl添加到「身份验证」页面的「登出重定向URL」列表中,否则B2C会拒绝重定向请求。
  2. 避免手动拼接URL:依赖中间件从配置文件中自动获取B2C的登出终结点,防止因租户ID、策略名称拼写错误导致的异常。
  3. 匹配Scheme名称:确保代码中使用的AzureADB2CDefaults相关Scheme,与Program.cs/Startup.cs中认证服务配置的Scheme完全一致。
  4. 测试验证:使用浏览器隐私模式测试登出流程,避免浏览器缓存的SSO会话干扰测试结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:52:46