共用方式為


教學課程:在 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 元件將用來顯示應用程式的主要內容,並可加以自定義,以包含您想要在應用程式的每個頁面上顯示的任何其他內容。 使用者的檔案資訊將透過 props 傳遞並顯示。

  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. 儲存檔案。

後續步驟