教程:在 React 单页应用中添加登录和注销功能组件

适用于:带白色勾号的绿色圆圈。 员工租户 带白色勾号的绿色圆圈。 外部租户(了解详细信息

在本教程中,你将配置 React 单页应用程序(SPA)进行身份验证。 在本系列的第 1 部分中,你创建了 React SPA,并准备好了它进行身份验证。 本教程介绍如何将 Microsoft身份验证库(MSAL) 功能组件添加到应用,并为应用生成响应式用户界面(UI)。

在本教程中,你将:

  • 将功能组件添加到应用程序
  • 创建显示用户配置文件信息的方法
  • 创建显示登录和注销体验的布局
  • 添加登录和退出登录体验

先决条件

将功能组件添加到应用程序

功能组件是 React 应用的构建基块,用于在应用程序中生成登录和注销体验。

添加 NavigationBar 组件

导航栏将为应用提供登录和注销体验。 以前在 index.js 文件中设置的实例变量将用于调用登录和注销方法,该方法会将用户重定向到登录页。

  1. 打开 src/components/NavigationBar.jsx 并添加以下代码片段:

    import { AuthenticatedTemplate, UnauthenticatedTemplate, useMsal } from '@azure/msal-react';
    import { Navbar, Button } from 'react-bootstrap';
    import { loginRequest } from '../authConfig';
    
    export const NavigationBar = () => {
        const { instance } = useMsal();
    
        const handleLoginRedirect = () => {
            instance.loginRedirect(loginRequest).catch((error) => console.log(error));
        };
    
        const handleLogoutRedirect = () => {
            instance.logoutRedirect().catch((error) => console.log(error));
        };
    
        /**
         * Most applications will need to conditionally render certain components based on whether a user is signed in or not.
         * msal-react provides 2 easy ways to do this. AuthenticatedTemplate and UnauthenticatedTemplate components will
         * only render their children if a user is authenticated or unauthenticated, respectively.
         */
        return (
            <>
                <Navbar bg="primary" variant="dark" className="navbarStyle">
                    <a className="navbar-brand" href="/">
                        Microsoft identity platform
                    </a>
                    <AuthenticatedTemplate>
                        <div className="collapse navbar-collapse justify-content-end">
                            <Button variant="warning" onClick={handleLogoutRedirect}>
                                Sign out
                            </Button>
                        </div>
                    </AuthenticatedTemplate>
                    <UnauthenticatedTemplate>
                        <div className="collapse navbar-collapse justify-content-end">
                            <Button onClick={handleLoginRedirect}>Sign in</Button>
                        </div>
                    </UnauthenticatedTemplate>
                </Navbar>
            </>
        );
    };
    
  2. 保存文件。

添加 PageLayout 组件

PageLayout 组件将用于显示应用的主要内容,并且可以自定义,以包含要在应用的每个页面上显示的任何其他内容。 用户的个人资料信息将通过属性传递信息来显示。

  1. 打开 src/components/PageLayout.jsx 并添加以下代码片段;

    import { AuthenticatedTemplate } from '@azure/msal-react';
    
    import { NavigationBar } from './NavigationBar.jsx';
    
    export const PageLayout = (props) => {
        /**
         * Most applications will need to conditionally render certain components based on whether a user is signed in or not.
         * msal-react provides 2 easy ways to do this. AuthenticatedTemplate and UnauthenticatedTemplate components will
         * only render their children if a user is authenticated or unauthenticated, respectively.
         */
        return (
            <>
                <NavigationBar />
                <br />
                <h5>
                    <center>Welcome to the Microsoft Authentication Library For React Tutorial</center>
                </h5>
                <br />
                {props.children}
                <br />
                <AuthenticatedTemplate>
                    <footer>
                        <center>
                            How did we do?
                            <a
                                href="https://forms.office.com/Pages/ResponsePage.aspx?id=v4j5cvGGr0GRqy180BHbR_ivMYEeUKlEq8CxnMPgdNZUNDlUTTk2NVNYQkZSSjdaTk5KT1o4V1VVNS4u"
                                rel="noopener noreferrer"
                                target="_blank"
                            >
                                {' '}
                                Share your experience!
                            </a>
                        </center>
                    </footer>
                </AuthenticatedTemplate>
            </>
        );
    }
    
  2. 保存文件。

添加 DataDisplay 组件

DataDisplay 组件将用于显示用户的配置文件信息和声明表,将在本教程的下一部分创建。 该 IdTokenData 组件将用于在 ID 令牌中显示声明。

  1. 打开 src/components/DataDisplay.jsx 并添加以下代码片段;

    import { Table } from 'react-bootstrap';
    import { createClaimsTable } from '../utils/claimUtils';
    
    import '../styles/App.css';
    
    export const IdTokenData = (props) => {
        const tokenClaims = createClaimsTable(props.idTokenClaims);
    
        const tableRow = Object.keys(tokenClaims).map((key, index) => {
            return (
                <tr key={key}>
                    {tokenClaims[key].map((claimItem) => (
                        <td key={claimItem}>{claimItem}</td>
                    ))}
                </tr>
            );
        });
        return (
            <>
                <div className="data-area-div">
                    <p>
                        See below the claims in your <strong> ID token </strong>. For more information, visit:{' '}
                        <span>
                            <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/id-tokens#claims-in-an-id-token">
                                docs.microsoft.com
                            </a>
                        </span>
                    </p>
                    <div className="data-area-div">
                        <Table responsive striped bordered hover>
                            <thead>
                                <tr>
                                    <th>Claim</th>
                                    <th>Value</th>
                                    <th>Description</th>
                                </tr>
                            </thead>
                            <tbody>{tableRow}</tbody>
                        </Table>
                    </div>
                </div>
            </>
        );
    };
    
  2. 保存文件。

后续步骤