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

基于AWS Amplify的Angular应用SSO配置咨询(自定义登录页)

将Angular Amplify应用作为自定义SSO登录服务的实现方案

1. 调整Amplify OAuth配置

在amplifyconfiguration.json中更新OAuth相关参数,指定允许的登录/登出回调地址(包含外部应用域名),并设置授权流程类型:

"oauth": {
  "domain": "your-cognito-auth-domain.auth.your-region.amazoncognito.com",
  "scope": ["email", "openid", "profile"],
  "redirectSignIn": ["https://your-angular-app.com/login", "https://external-app-1.com/callback", "https://external-app-2.com/callback"],
  "redirectSignOut": ["https://your-angular-app.com/logout", "https://external-app-1.com/logout-callback"],
  "responseType": "code"
}

注:这里的domain是你的Cognito用户池域名,用于处理OAuth核心流程,即使不用托管UI也需要配置。

2. 自定义登录页处理OAuth跳转请求

外部应用跳转至你的登录页时,会携带client_id、redirect_uri、response_type、state等OAuth参数,需在登录组件中捕获并在登录成功后完成回调:

捕获URL参数

import { ActivatedRoute } from '@angular/router';
import { Auth } from 'aws-amplify';

export class LoginComponent {
  private oauthParams: any;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.oauthParams = params;
    });
  }
}

登录成功后触发回调

async handleLogin(username: string, password: string) {
  try {
    const user = await Auth.signIn(username, password);
    const cognitoUser = user.getCognitoUser();
    const session = await cognitoUser.getSession();

    if (this.oauthParams) {
      // 构造授权码请求,跳转至Cognito授权端点后自动重定向到外部应用
      const authRedirectUrl = `https://your-cognito-auth-domain.auth.your-region.amazoncognito.com/oauth2/authorize?response_type=${this.oauthParams.response_type}&client_id=${this.oauthParams.client_id}&redirect_uri=${encodeURIComponent(this.oauthParams.redirect_uri)}&state=${this.oauthParams.state}&id_token=${session.getIdToken().getJwtToken()}`;
      window.location.href = authRedirectUrl;
    } else {
      // 常规登录后跳转至应用主页
      this.router.navigate(['/dashboard']);
    }
  } catch (err) {
    console.error('登录失败:', err);
  }
}

3. 配置Cognito用户池应用客户端

在AWS控制台的Cognito用户池管理界面,找到对应应用客户端:

  • 启用授权码授予流程
  • 将所有外部应用的redirect_uri添加至允许的回调URL列表
  • 取消勾选“使用Cognito托管UI”选项
  • 根据需求调整令牌有效期(ID Token、Access Token)

4. 外部应用跳转逻辑

外部应用需构造如下格式的URL跳转至你的Angular登录页:

https://your-angular-app.com/login?client_id=EXTERNAL_APP_CLIENT_ID&redirect_uri=https://external-app.com/callback&response_type=code&state=RANDOM_CSRF_VALUE

注:state参数用于防止CSRF攻击,外部应用需保存该值并在回调时验证。

5. 处理登出回调

在自定义登出组件中,完成Amplify登出后跳转回外部应用:

async handleLogout() {
  await Auth.signOut();
  this.route.queryParams.subscribe(params => {
    const logoutRedirect = params['logout_redirect_uri'];
    if (logoutRedirect) {
      window.location.href = logoutRedirect;
    } else {
      this.router.navigate(['/login']);
    }
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 00:00:28