次の方法で共有


チュートリアル: React シングル ページ アプリでサインインとサインアウト機能コンポーネントを追加する

このチュートリアルでは、認証用に React シングルページ アプリケーション (SPA) を構成します。 このシリーズ パート 1 では、React SPA を作成し、認証用に準備しました。 このチュートリアルでは、microsoft Authentication Library (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. ファイルを保存します。

次の手順

チュートリアル: React SPA にサインインしてサインアウトする