자습서: 외부 테넌트에 대한 React SPA에 로그인 및 로그아웃 추가
이 자습서는 React SPA(단일 페이지 애플리케이션)를 빌드하고 Microsoft Entra 관리 센터를 사용하여 인증을 준비하는 방법을 보여 주는 시리즈의 마지막 부분입니다. 이 시리즈의 3부에서는 Visual Studio Code에서 React SPA를 만들고 인증하도록 구성했습니다. 이 마지막 단계에서는 앱에 로그인 및 로그아웃 기능을 추가하는 방법을 보여 줍니다.
이 자습서에서는 다음을 수행합니다.
- 페이지 레이아웃을 만들고 로그인 및 로그아웃 환경을 추가합니다.
- 인증된 정보를 렌더링하는 기본 함수를 바꿉니다.
- 사용자 흐름을 사용하여 애플리케이션에 로그인 및 로그아웃
필수 조건
파일명 변경 및 인증된 정보 렌더링 함수 추가
기본적으로 애플리케이션은 App.js라는 JavaScript 파일을 통해 실행됩니다. 개발자가 React에서 HTML을 작성할 수 있도록 하는 확장인 .jsx로 변경해야 합니다.
App.js가 App.jsx로 이름이 바뀌었는지 확인합니다.
기존 코드를 다음 코드 조각으로 바꿉니다.
import { MsalProvider, AuthenticatedTemplate, useMsal, UnauthenticatedTemplate } from '@azure/msal-react'; import { Container, Button } from 'react-bootstrap'; import { PageLayout } from './components/PageLayout'; import { IdTokenData } from './components/DataDisplay'; import { loginRequest } from './authConfig'; import './styles/App.css'; /** * 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. For more, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md */ const MainContent = () => { /** * useMsal is hook that returns the PublicClientApplication instance, * that tells you what msal is currently doing. For more, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/hooks.md */ const { instance } = useMsal(); const activeAccount = instance.getActiveAccount(); const handleRedirect = () => { instance .loginRedirect({ ...loginRequest, prompt: 'create', }) .catch((error) => console.log(error)); }; return ( <div className="App"> <AuthenticatedTemplate> {activeAccount ? ( <Container> <IdTokenData idTokenClaims={activeAccount.idTokenClaims} /> </Container> ) : null} </AuthenticatedTemplate> <UnauthenticatedTemplate> <Button className="signInButton" onClick={handleRedirect} variant="primary"> Sign up </Button> </UnauthenticatedTemplate> </div> ); }; /** * msal-react is built on the React context API and all parts of your app that require authentication must be * wrapped in the MsalProvider component. You will first need to initialize an instance of PublicClientApplication * then pass this to MsalProvider as a prop. All components underneath MsalProvider will have access to the * PublicClientApplication instance via context as well as all hooks and components provided by msal-react. For more, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md */ const App = ({ instance }) => { return ( <MsalProvider instance={instance}> <PageLayout> <MainContent /> </PageLayout> </MsalProvider> ); }; export default App;
프로젝트 실행 및 로그인
필요한 모든 코드 조각이 추가되었으므로 이제 웹 브라우저에서 애플리케이션을 테스트할 수 있습니다.
애플리케이션이 이미 터미널에서 실행되고 있어야 합니다. 그렇지 않은 경우 다음 명령을 실행하여 앱을 시작합니다.
npm start
자동으로 리디렉션되지 않으면 웹 브라우저를 열고
http://localhost:3000/
으로 이동합니다.이 자습서에서는 팝업을 사용하여 로그인 옵션을 선택합니다.
로그인 옵션이 포함된 팝업 창이 나타나면 로그인할 계정을 선택합니다.
코드가 이메일 주소로 전송된다는 것을 나타내는 두 번째 창이 나타날 수 있습니다. 이런 경우에는 코드 보내기를 선택합니다. 보낸 사람 Microsoft 계정 팀에서 보낸 메일을 열고 일곱 자리 일회용 코드를 입력합니다. 입력한 후 로그인을 선택합니다.
로그인 상태 유지에서 아니요 또는 예를 선택할 수 있습니다.
앱은 로그인하고 데이터에 액세스할 수 있는 권한을 요청합니다. 수락을 선택하여 계속합니다.
애플리케이션에서 로그아웃
- 애플리케이션에서 로그아웃하려면 탐색 모음에서 로그아웃을 선택합니다.
- 로그아웃할 계정을 묻는 창이 나타납니다.
- 로그아웃에 성공하면 모든 브라우저 창을 닫으라는 최종 창이 나타납니다.