首页 > 解决方案 > 如何使用 AWS Amplify 和 Cognito 创建独立的身份验证站点?

问题描述

我有三个反应网络应用程序。两个是平台,一个是独立的登录/注册。我希望能够登录 auth ui 并在两个平台之间导航,而无需额外登录。现在我已经设置为使用 AWS Amplify 在身份验证 UI 中登录/注册。但是我不确定在访问两个平台 Web 应用程序时如何保持登录状态。我计划让它们都在同一个域下,但也使用子域。例如,auth.domain.com、admin.domain.com 和 customer.domain.com。

我对 AWS Amplify 很陌生,我以前的所有应用程序都内置了身份验证,所以这是我第一次尝试将身份验证与主应用程序分离。我真的在寻找前进的方向或教程(如果存在)。

谢谢你的帮助。

标签: reactjsamazon-web-servicesamazon-cognitoaws-amplify

解决方案


所以你有你的 LoginPage 来处理登录,你还有一些其他的页面,你只让人们在登录时看到。这是在功能组件中执行此操作的一种方法。

在较高级别,您有一个管理身份验证状态的状态。默认情况下,它被初始化为加载。然后你Auth.currentAuthenticatedUser()用来检查用户是否登录。如果是,您将它们暴露给页面内容。如果没有,您将他们引导到登录页面。

import React, { useState, useEffect } from 'react';
import { Redirect } from "react-router"; //Using react-router for page navigation for example
import { Auth, Hub} from 'aws-amplify';

const OtherPage = () =>{
    // Default at loading state
    const [authState, setAuthState] = useState('loading');

    // Use effect is run when component loading is mounted
    useEffect((data) => {
        // Define updateAuthState
        let updateAuthState = async () => {
            try {
                // Get current auth user, this throw error if not authenticated
                let user = await Auth.currentAuthenticatedUser();
                // No error, change auth state to show page content
                setAuthState("authenticated");
           }
           catch(error){
               // Error, change auth state to redirect user to login page
               setAuthState("unauthenticated");
           }
       }
       // Call AuthState Once
       updateAuthState();
       // Set up Hub to listen for auth event in case user log out
       Hub.listen('auth', updateAuthStat);
       return () => Hub.remove('auth', updateAuthState); // cleanup
    }

    // Do different things based on authState
    switch (authState) {
        case 'loading':
            return <h1>Loading...</h1>;
        case 'authenticated':
            return <h1>Your authenticated component</h1>;
        case 'unauthenticated':
            return <Redirect to="/login" />; {/*I recommend using /login for your login page */}
        default:
            return null;
    }
}

export default OtherPage;

住所代码是我汇总的简化版本,我还没有测试过,但高层次的想法就在那里:)

有关更多信息,我建议查看 Nader Dabit 的使用 Amplify 框架进行用户身份验证的完整指南 [ https://dev.to/dabit3/the-complete-guide-to-user-authentication-with-the-amplify-framework -2inh]和他的免费视频 [ https://egghead.io/lessons/react-install-configure-the-aws-amplify-cli]


推荐阅读