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

调用Cognito AdminUserGlobalSignOut后如何强制多设备跳转登录页

如何强制所有设备上的Cognito用户跳转到登录页

调用AdminUserGlobalSignOut只会吊销用户的所有刷新令牌,但不会主动通知前端会话失效——桌面端能自动跳转,大概率是因为它的请求拦截器或Auth库已经处理了令牌无效的401响应,而移动端Web应用缺少对应的处理逻辑。要实现全设备强制跳转,需要从前端逻辑和后端配合两方面入手:

1. 前端全局拦截无效令牌响应

给所有API请求添加拦截器,一旦捕获到401未授权或令牌验证失败的错误,立即执行登出并跳转登录页:

// 以Axios拦截器为例
axios.interceptors.response.use(
  response => response,
  async error => {
    if (error.response.status === 401) {
      // 清除本地存储的令牌信息
      localStorage.removeItem('cognitoToken');
      // 跳转登录页
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

如果用AWS Amplify,可以直接在API调用时捕获会话无效的异常:

import { Auth } from 'aws-amplify';

// 封装API调用函数
async function callApi(endpoint) {
  try {
    const session = await Auth.currentSession();
    const token = session.getIdToken().getJwtToken();
    const response = await fetch(endpoint, {
      headers: { Authorization: `Bearer ${token}` }
    });
    if (!response.ok) {
      if (response.status === 401) {
        await Auth.signOut();
        window.location.href = '/login';
      }
      throw new Error('API请求失败');
    }
    return response.json();
  } catch (err) {
    // 捕获会话无效的异常(比如令牌已被吊销)
    if (err.name === 'NotAuthorizedException') {
      await Auth.signOut();
      window.location.href = '/login';
    }
    throw err;
  }
}

2. 定时主动校验会话有效性

移动端Web应用可能长时间处于后台或未发起请求,这时定时检查会话状态能及时发现令牌失效:

// 每5分钟检查一次会话
setInterval(async () => {
  try {
    const session = await Auth.currentSession();
    // 验证会话是否有效(Cognito SDK自带的校验)
    if (!session.isValid()) {
      await Auth.signOut();
      window.location.href = '/login';
    }
  } catch (err) {
    // 捕获到会话不存在或无效的错误,直接登出跳转
    await Auth.signOut();
    window.location.href = '/login';
  }
}, 300000); // 300000毫秒=5分钟

3. 后端配合推送失效通知(可选)

如果你的应用有WebSocket服务,可以在调用AdminUserGlobalSignOut后,向该用户的所有在线会话推送登出指令:

  • 调用AdminUserGlobalSignOut成功后,通过WebSocket服务发送消息给该用户的所有连接
  • 前端WebSocket监听器收到消息后,立即执行登出和跳转逻辑

这种方式能实现近乎实时的全设备登出跳转,适合对时效性要求高的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:55:39