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

React集成AWS Amplify+Cognito+Azure AD联合登录异常求助

问题:React + AWS Cognito + Azure AD 联合认证跳转失败

背景

正在为内部单页应用(SPA)实现基于React、AWS Cognito用户池、Azure AD的认证功能,已按AWS官方指南完成Cognito用户池与Azure AD的联合认证配置,React端基于aws-amplify v6.0.4开发,但点击登录按钮后出现错误页面,无法完成认证流程。

代码示例

import React, { useEffect, useState } from "react";

import { Amplify } from "aws-amplify";
import { Hub } from "aws-amplify/utils";
import { signInWithRedirect, signOut, getCurrentUser } from "aws-amplify/auth";
import { AuthUser } from "aws-amplify/auth";

Amplify.configure({
  Auth: {
    Cognito: {
      //  Amazon Cognito User Pool ID
      userPoolId: "XX-xxxx-#_XXXXXXXXXX",
      // OPTIONAL - Amazon Cognito Web Client ID (26-char alphanumeric string)
      userPoolClientId: "xxxxxxxxxxxxxxxxxx",
      // REQUIRED only for Federated Authentication - Amazon Cognito Identity Pool ID
      // identityPoolId: "XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab",
      // OPTIONAL - This is used when autoSignIn is enabled for Auth.signUp
      // 'code' is used for Auth.confirmSignUp, 'link' is used for email link verification
      signUpVerificationMethod: "code", // 'code' | 'link'
      loginWith: {
        // OPTIONAL - Hosted UI configuration
        oauth: {
          domain:
            "https://my-userpool.auth.us-east-2.amazoncognito.com",
          scopes: ["email", "openid"],
          redirectSignIn: ["http://localhost:3000/"],
          redirectSignOut: ["http://localhost:3000/"],
          responseType: "code", // or 'token', note that REFRESH token will only be generated when the responseType is code
        },
      },
    },
  },
});

export default function RootApp() {
  const [user, setUser] = useState<AuthUser | null>(null);

  useEffect(() => {
    const unsubscribe = Hub.listen("auth", ({ payload }) => {
      switch (payload.event) {
        case "signInWithRedirect":
          getUser();
          break;
        case "signInWithRedirect_failure":
          console.log("An error has ocurred during the Oauth flow.");
          break;
      }
    });

    getUser();

    return unsubscribe;
  }, []);

  const getUser = async (): Promise<void> => {
    try {
      const currentUser = await getCurrentUser();
      setUser(currentUser);
    } catch (error) {
      console.error(error);
      console.log("Not signed in");
    }
  };

  return user !== null ? (
    <AuthenticatedApp user={user}></AuthenticatedApp>
  ) : (
    <UnauthenticatedApp />
  );
}

function UnauthenticatedApp() {
  return (
    <div>
      <div className="App">
        <button
          onClick={
            () =>
              signInWithRedirect({ provider: { custom: "MyAD" } }) //MyAD is identity provider name in AWS cognito
          }
        >
          Log in
        </button>
      </div>
    </div>
  );
}

interface Props {
  user: AuthUser;
}

function AuthenticatedApp({ user }: Props) {
  return (
    <div>
      <button onClick={() => signOut()}>Sign Out</button>
      <div>{user?.username}</div>
    </div>
  );
}

错误截图

登录错误页面

解决方向建议

  • 检查Cognito用户池客户端配置:
    • 确认用户池客户端的OAuth 2.0设置中,redirectSignIn和redirectSignOut已包含http://localhost:3000/,且勾选了Authorization code grant授权类型(与代码中responseType: "code"匹配)
    • 确认客户端已启用"MyAD"这个自定义身份提供商,在用户池客户端的"身份提供商"选项中已添加该IDP
  • 检查Azure AD应用注册配置:
    • 确认Azure AD应用的重定向URI设置为Cognito Hosted UI的回调地址,格式为https://<你的Cognito域名>/oauth2/idpresponse
    • 确认Azure AD应用已添加openid、email权限,且内部应用已完成管理员同意
  • 修正Amplify配置细节:
    • 将domain配置改为不带https://的纯域名:my-userpool.auth.us-east-2.amazoncognito.com
    • 确认provider: { custom: "MyAD" }中的"MyAD"与Cognito用户池里身份提供商的名称完全一致(区分大小写)
  • 查看详细错误日志:
    • 登录AWS控制台,进入Cognito用户池,查看监控下的日志或关联的CloudWatch日志组,获取具体错误原因
    • 打开浏览器开发者工具,查看Network请求的错误状态码和Console中的报错信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 20:35:34