자습서: React 단일 페이지 앱에서 로그인 및 로그아웃 기능 구성 요소 추가
이 자습서에서는 인증을 위해 React SPA(단일 페이지 애플리케이션)를 구성합니다. 이 시리즈 1부에서는 React SPA를 만들고 인증을 위해 준비했습니다. 이 자습서에서는 MSAL(Microsoft 인증 라이브러리) 기능 구성 요소를 앱에 추가하고 앱에 대한 반응형 UI(사용자 인터페이스)를 빌드하여 인증 흐름을 추가하는 방법을 알아봅니다.
이 자습서에서는 다음을 수행합니다.
- 애플리케이션에 기능 구성 요소 추가
- 사용자의 프로필 정보를 표시하는 방법 만들기
- 로그인 및 로그아웃 환경을 표시하는 레이아웃 만들기
- 로그인 및 로그아웃 환경 추가
필수 구성 요소
- 자습서의 필수 구성 요소 및 단계 완료: 인증애플리케이션 준비.
애플리케이션에 기능 구성 요소 추가
기능 구성 요소는 React 앱의 구성 요소이며 애플리케이션에서 로그인 및 로그아웃 환경을 빌드하는 데 사용됩니다.
NavigationBar 구성 요소 추가
탐색 모음은 앱에 대한 로그인 및 로그아웃 환경을 제공합니다. index.js 파일에 이전에 설정된 인스턴스 변수는 로그인 및 로그아웃 메서드를 호출하는 데 사용됩니다. 그러면 사용자를 다시 로그인 페이지로 리디렉션합니다.
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> </> ); };
파일을 저장합니다.
PageLayout 구성 요소 추가
PageLayout 구성 요소는 앱의 기본 콘텐츠를 표시하는 데 사용되며 앱의 모든 페이지에 표시하려는 추가 콘텐츠를 포함하도록 사용자 지정할 수 있습니다. 사용자의 프로필 정보는 props를 통해 정보를 전달하여 표시됩니다.
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> </> ); }
파일을 저장합니다.
DataDisplay 구성 요소 추가
DataDisplay
구성 요소는 자습서의 다음 섹션에서 만들어질 사용자의 프로필 정보와 클레임 테이블을 표시하는 데 사용됩니다.
IdTokenData
구성 요소는 ID 토큰에 클레임을 표시하는 데 사용됩니다.
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> </> ); };
파일을 저장합니다.
다음 단계
자습서: React SPA 로그인 및 로그아웃