1

我在我的反应应用程序中成功地使用托管 ui 的 Cognito 联合登录。此登录流程重定向到我的应用程序中的登录 url。我的意图是在请求中出现 auth_code 时在useEffect挂钩中获取 Auth.currentAuthenticatedUser()(现在只是查看搜索组件是否有任何值),然后重定向到另一条路线。

我遇到的问题是Amplify 在幕后进行的https://foo-api.auth.us-east-1.amazoncognito.com/oauth2/token调用直到 Auth.currentAuthenticatedUser 承诺之后才会返回以失败解决。

我天真的解决方法/解决方案是将调用包装在一个计时器中,见下文。这工作正常,但似乎脆弱和错误的头脑(即使我处理了无限调用的可能性)。

import React, { useEffect } from "react";
import {useLocation, useHistory} from "react-router-dom"
import Auth from "@aws-amplify/auth";
import { CognitoHostedUIIdentityProvider } from "@aws-amplify/auth/lib-esm/types";


const App = () => {

  useAuthentication();

  function useAuthentication() {
    const location = useLocation()
    const history = useHistory()
    useEffect(_ => {
      if(location.search) {
        const interval = setInterval(() => {
          Auth.currentAuthenticatedUser()
          .then(_=> history.push('/'))
          .catch(console.log)
        }, 1000)
        return _ => clearInterval(interval)
      }
    }, [location]);
  }

  return (
    <div className="App">
      <button
        type="button"
        onClick={() =>
          Auth.federatedSignIn({
            provider: CognitoHostedUIIdentityProvider.Cognito
          })
        }
      >
        Federated sign in
      </button>
    </div>
  );
};

export default App;

这看起来几乎像一个放大错误,至少当我试图这样使用它时。我看到这里出现了这个问题:AWS Cognito hosts UI and Amplify Auth with authorization code OAuth flow。但我没有使用任何其他 Amplify 组件,例如 Hub。

有没有更好、更惯用的方法来处理这种情况?

4

0 回答 0