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

基于AWS Amplify与Angular 15实现多应用单点登录方案问询

同域名下Angular应用共享Cognito登录状态方案

问题根源

你遇到的核心问题是:虽然两个应用共用同一Cognito资源,但Amplify默认的凭证存储逻辑可能因应用配置差异(或隐式前缀)导致跨应用无法读取已登录状态。Auth.currentAuthenticatedUser()返回空,说明appB无法读取appA存在本地的凭证数据。

解决方案步骤

1. 确保两个应用的Amplify配置完全一致

两个应用必须使用完全相同的Amplify Auth配置,尤其是用户池ID、App Client ID、身份池ID这几个核心参数,同时显式指定存储方式为localStorage(同域名下默认共享)。

创建统一的配置文件(两个应用复用):

// src/app/amplify-config.ts
import { Amplify } from 'aws-amplify';

export const amplifyConfig = {
  Auth: {
    region: '你的AWS区域',
    userPoolId: '你的Cognito用户池ID',
    userPoolWebClientId: '你的Cognito App Client ID',
    identityPoolId: '你的Cognito身份池ID',
    // 强制使用localStorage,确保同域名下跨应用共享
    storage: window.localStorage,
    // 可选:统一存储键前缀,避免不同应用隐式生成不同前缀
    storageKeyPrefix: 'shared-cognito-session-'
  }
};

// 在main.ts中初始化Amplify
Amplify.configure(amplifyConfig);

2. 在appB中实现自动凭证验证逻辑

在appB的根组件初始化时,先尝试读取本地缓存的凭证,验证有效性后自动登录,无需跳转登录页。

// src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { Auth } from 'aws-amplify';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private router: Router) {}

  async ngOnInit() {
    try {
      // 从本地缓存读取已认证用户,不跳过缓存
      const user = await Auth.currentAuthenticatedUser({ bypassCache: false });
      // 验证会话有效性,自动处理令牌刷新
      const session = await Auth.currentSession();
      
      if (session.isValid()) {
        // 会话有效,跳转到应用主页
        this.router.navigate(['/dashboard']);
      } else {
        // 令牌过期,尝试自动刷新
        await Auth.refreshSession(user.signInUserSession.refreshToken);
        this.router.navigate(['/dashboard']);
      }
    } catch (error) {
      // 无有效凭证,跳转到登录页
      this.router.navigate(['/login']);
    }
  }
}

3. 关键注意事项

  • 版本一致性:两个应用必须使用完全相同版本的aws-amplify(v5)和@aws-amplify/ui-angular(v4),版本差异会导致凭证存储格式不兼容。
  • Cognito配置:确保你的Cognito App Client已启用令牌刷新功能,且refresh token的有效期符合业务需求。
  • 浏览器隐私设置:确认用户浏览器未禁用localStorage(同域名下不属于第三方存储,默认允许)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 12:42:47