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

集成ALB时如何触发AWS Cognito用户登出?

解决ALB+Cognito登出后自动回到首页的问题

核心问题分析

  • ALB完成认证后会生成专属的认证会话Cookie(命名格式通常为AWSELBAuthSessionCookie-0这类),你的现有代码仅清除了普通Cookie和请求头,未处理这个ALB专属Cookie,导致ALB仍判定会话有效,直接跳过认证环节放行到应用首页。
  • AdminUserGlobalSignOutAsync仅会撤销用户的refresh token,不会影响ALB已生成的会话Cookie——两者属于独立的会话机制,必须分别处理。

正确登出流程步骤

  1. 撤销Cognito端的用户令牌:保留AdminUserGlobalSignOutAsync调用,确保用户无法通过refresh token获取新的访问令牌。
  2. 强制过期ALB认证会话Cookie:针对ALB生成的认证Cookie设置过期时间,彻底销毁ALB侧的会话。
  3. 重定向到Cognito登出端点:使用正确参数触发Cognito清除自身会话,再跳转回指定地址。

具体代码实现

1. 处理ALB认证Cookie过期

在.NET 6中,需要精准定位ALB认证Cookie并强制设置过期:

// 遍历所有Cookie,重点处理ALB认证会话Cookie
foreach (var cookieKey in Request.Cookies.Keys)
{
    if (cookieKey.StartsWith("AWSELBAuthSessionCookie-"))
    {
        // 先删除原有Cookie,再追加一个已过期的空Cookie确保浏览器彻底清除
        Response.Cookies.Delete(cookieKey);
        var expiredCookieOpts = new CookieOptions
        {
            Expires = DateTimeOffset.UtcNow.AddDays(-1),
            Path = "/",
            Domain = Request.Host.Host, // 需匹配ALB设置Cookie的域名,子域名场景要对应调整
            HttpOnly = true,
            Secure = true // 生产环境必须启用,本地测试可根据环境调整
        };
        Response.Cookies.Append(cookieKey, "", expiredCookieOpts);
    }
    else
    {
        // 清除其他普通业务Cookie
        Response.Cookies.Delete(cookieKey);
    }
}

2. 修正Cognito登出重定向URL

登出URL不需要response_type=code参数,正确格式如下:

https://{domain}.auth.{region}.amazoncognito.com/logout?client_id={clientid}&logout_uri={redirect_uri}&scope=openid

注意:logout_uri必须提前配置在Cognito应用客户端的已注销URL列表中,否则Cognito会拒绝跳转请求。

3. 完整登出方法示例

public async Task<IActionResult> Logout()
{
    // 1. 调用Cognito API撤销用户令牌
    var cognitoClient = new AmazonCognitoIdentityProviderClient();
    var signOutRequest = new AdminUserGlobalSignOutRequest
    {
        UserPoolId = "your-userpool-id",
        Username = User.Identity.Name // 从当前认证用户上下文获取用户名
    };
    await cognitoClient.AdminUserGlobalSignOutAsync(signOutRequest);

    // 2. 清理所有Cookie,重点处理ALB认证Cookie
    foreach (var cookieKey in Request.Cookies.Keys)
    {
        if (cookieKey.StartsWith("AWSELBAuthSessionCookie-"))
        {
            Response.Cookies.Delete(cookieKey);
            var expiredOpts = new CookieOptions
            {
                Expires = DateTimeOffset.UtcNow.AddDays(-1),
                Path = "/",
                Domain = Request.Host.Host,
                HttpOnly = true,
                Secure = true
            };
            Response.Cookies.Append(cookieKey, "", expiredOpts);
        }
        else
        {
            Response.Cookies.Delete(cookieKey);
        }
    }

    // 3. 构造并跳转至Cognito登出端点
    var cognitoDomain = "your-domain.auth.your-region.amazoncognito.com";
    var clientId = "your-client-id";
    var logoutRedirectUri = Url.Action("Login", "Account", null, Request.Scheme); // 跳转回应用登录页
    var encodedRedirectUri = Uri.EscapeDataString(logoutRedirectUri);
    var logoutUrl = $"https://{cognitoDomain}/logout?client_id={clientId}&logout_uri={encodedRedirectUri}&scope=openid";
    
    return Redirect(logoutUrl);
}

额外注意事项

  • Cognito配置校验:确认logout_uri已添加到应用客户端的「已注销URL」列表,否则Cognito会拦截跳转。
  • 令牌有效性:即使启用Enable token revocation,已颁发的访问令牌在有效期内仍可使用,但AdminUserGlobalSignOutAsync会让refresh token失效,用户无法获取新令牌。
  • HTTPS环境:生产环境下ALB的Cookie默认启用Secure属性,代码中需保持Secure = true,否则Cookie无法被正确操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:43:16