如何在不使用 Amplify 的情况下使用 Amazon Cognito

Mic*_*ott 17 amazon-web-services amazon-cognito amplify

我现在刚刚进入 Cognito。AWS 设置相当简单直接。

我们有各种各样的应用程序、网络应用程序和服务,我们希望它们能够使用 Cognito 服务。我有使用 Auth0 进行类似设置的经验,但由于我们一直在利用许多 Amazon Web Services,因此使用 Cognito 也确实很有意义。

我所到之处,每个指南最终都引用了 Amplify 客户端库和 cli。我们有现有的应用程序和服务,真的不想改变工具或导入任何不必要的东西来增加膨胀和复杂性。有没有办法在没有 Amplify 库的情况下使用 Cognito 服务?是否有用于与 Cognito 服务、身份验证和授权流程交互的轻量级仅 Cognito 客户端库?

oie*_*elo 17

首先,我想澄清“放大”是多个事物的总称。我们有:

  1. 放大库 (UI/JS)
  2. 放大 CLI(创建云原生应用程序)
  3. Amplify 控制台(全栈 Web 应用程序的 ci/cd 和托管)
  4. Amplify Admin UI(用于创建和配置全栈 Web 应用程序的 UI)

您可以查看主页以获取更多说明 - https://docs.amplify.aws/

是否有用于与 Cognito 服务、身份验证和授权流程交互的轻量级仅 Cognito 客户端库?

在幕后,Amplify 使用amazon-cognito-identity-js库与 Amazon Cognito 交互。您可以直接通过npm install amazon-cognito-identity-js.

源代码已移至Amplify 库(例如 amplify-js)存储库。再次是第一类“放大库”下的“放大”伞的一部分。

有没有办法在没有 Amplify 库的情况下使用 Cognito 服务?

您可以采用的另一种方法是使用 Amazon Cognito 作为 OAuth 服务器。当您创建Amazon Cognito 托管 UI 域时,它会为您提供符合 OAuth 2.0 的授权服务器。

您可以为注册/登录终端节点创建自己的 API/后端,并与 Amazon Cognito OAuth 服务器交换令牌/凭证,而无需使用aws-sdk或任何 3rd 方依赖库。

我写了一个演练示例,如何配置你的用户池,你需要使用 Node.js 与之交谈的端点,你可以在这里找到它:https : //github.com/oieduardorabelo/node-amazon-cognito-oauth

您可以对任何其他语言遵循相同的想法。


Mad*_*nai 5

作为对在 React 中使用 Amazon Cognito 而不使用 Amplify 主题的研究的结果,我遇到了这样一个沙箱。从路由器 5 切换到路由器 6 可能不会有问题。这里主要的金子就是这个钩子。其余的实现可以在沙箱中找到:https://codesandbox.io/s/cognito-forked-f02htu

const Pool_Data = {
  UserPoolId: "xxx",
  ClientId: "yyy"
};

export default function useHandler() {
  const [state, setstate] = useState({
    loading: false,
    isAuthenticated: false
  });

  const { loading, isAuthenticated } = state;

  const userPool = new CognitoUserPool(Pool_Data);

  const getAuthenticatedUser = useCallback(() => {
    return userPool.getCurrentUser();
  }, []);

  console.log(getAuthenticatedUser());

  useEffect(() => {
    getAuthenticatedUser();
  }, [getAuthenticatedUser]);

  const signOut = () => {
    return userPool.getCurrentUser()?.signOut();
  };
  console.log("I am here", getAuthenticatedUser()?.getUsername());

  return {
    loading,
    isAuthenticated,
    userPool,
    getAuthenticatedUser,
    signOut
  };
}
Run Code Online (Sandbox Code Playgroud)