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

如何配置Amplify Authenticator组件以使用外部身份提供商(IdP)登录?

配置Amplify Authenticator组件实现外部身份提供商(IdP)登录

问题

Amplify的Authenticator组件可快速集成AWS Cognito用户池认证,但默认不显示外部身份提供商(IdP)的登录入口。查阅官方文档仅找到Facebook这类社交提供商的配置示例,想了解如何配置该组件使用自定义外部IdP登录。

现有代码:

export default function App() {
  return (
    <Authenticator socialProviders={['amazon', 'apple', 'facebook', 'google']}>
      {({ signOut, user }) => (
        <main>
          <h1>Hello {user.username}</h1>
          <button onClick={signOut}>Sign out</button>
        </main>
      )}
    </Authenticator>
  );
}

解决步骤

1. 先在AWS Cognito控制台完成外部IdP配置

这是前提步骤,必须先在Cognito用户池内添加并配置目标外部IdP(如SAML/OIDC类型的企业级身份提供商):

  • 登录AWS控制台,进入目标Cognito用户池
  • 切换到「身份提供商」选项卡,选择需添加的IdP类型(SAML 2.0/OIDC)
  • 按照向导完成元数据导入、回调URL设置等配置
  • 进入「应用客户端设置」,开启该外部IdP作为登录选项

2. 自定义Authenticator组件添加外部IdP登录按钮

socialProviders属性仅支持Amplify预集成的社交平台,自定义外部IdP需通过Auth.federatedSignIn方法手动实现,同时自定义登录界面插槽:

import { Authenticator, Button } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';
import { Auth } from 'aws-amplify';

export default function App() {
  const handleExternalLogin = async () => {
    try {
      // 替换为你在Cognito中配置的外部IdP名称
      await Auth.federatedSignIn({ provider: 'YOUR_IDP_NAME' });
    } catch (err) {
      console.error('外部IdP登录失败:', err);
    }
  };

  return (
    <Authenticator>
      {({ signOut, user }) => (
        <main>
          <h1>Hello {user.username}</h1>
          <button onClick={signOut}>退出登录</button>
        </main>
      )}
      {/* 自定义登录界面,添加外部IdP按钮 */}
      {({ slots }) => (
        <>
          {slots.default}
          <div style={{ margin: '1rem auto', textAlign: 'center', width: '80%' }}>
            <Button onClick={handleExternalLogin} variation="primary">
              通过外部身份提供商登录
            </Button>
          </div>
        </>
      )}
    </Authenticator>
  );
}

3. 确认Amplify配置文件正确

若使用Amplify CLI配置,运行amplify update auth并选择添加外部身份提供商,CLI会自动更新amplifyconfiguration.json的配置内容;若手动配置,需确保文件包含外部IdP的相关配置信息。

注意事项

  • socialProviders仅适配Amplify预设的社交平台,自定义外部IdP不可使用该属性
  • 需保证Cognito中配置的回调URL与应用地址完全一致,否则会导致登录失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:16:26