자습서: React 단일 페이지 애플리케이션 만들기 및 인증 준비
에 적용: Workforce 사용자에게 흰색 확인 표시 기호가 있는 녹색 원이
외부 사용자(자세한 내용은에서 알아보기)
이 자습서에서는 React SPA(단일 페이지 애플리케이션)를 빌드하고 Microsoft ID 플랫폼을 사용하여 인증을 준비합니다. 이 자습서에서는 npm
사용하여 React SPA를 만들고, 인증 및 권한 부여에 필요한 파일을 만들고, 테넌트 세부 정보를 소스 코드에 추가하는 방법을 보여 줍니다. 애플리케이션은 직원 테넌트에 있는 직원 또는 외부 테넌트를 사용하는 고객에 사용할 수 있습니다.
이 자습서에서는 다음을 수행합니다.
- 새 React 프로젝트 만들기
- 인증에 필요한 패키지 설치
- 파일 구조를 만들고 서버 파일에 코드 추가
- 인증 구성 파일에 테넌트 세부 정보 추가
필수 구성 요소
- Node.js.
- Visual Studio Code 또는 다른 코드 편집기.
새 React 프로젝트 만들기
Visual Studio Code를 열고 파일>폴더 열기를 선택합니다.. 프로젝트의 위치로 이동하여 프로젝트를 만들 위치를 클릭합니다.
새 터미널터미널>선택하여 새 터미널을 엽니다.
다음 명령을 실행하여 reactspalocal 이름이새 React 프로젝트를 만들고, 새 디렉터리로 변경하고, React 프로젝트를 시작합니다. 웹 브라우저는 기본적으로 주소
http://localhost:3000/
로 열립니다. 브라우저는 열려 있고 저장된 모든 변경 내용에 대해 다시 렌더링됩니다.npx create-react-app reactspalocal cd reactspalocal npm start
다음 폴더 구조를 달성하기 위해 추가 폴더 및 파일을 만듭니다.
├─── public │ └─── index.html └───src └─── styles │ └─── App.css │ └─── index.css ├─── utils │ └─── claimUtils.js ├─── components │ └─── DataDisplay.jsx │ └─── NavigationBar.jsx │ └─── PageLayout.jsx └── App.jsx └── authConfig.js └── index.js
ID 및 부트스트랩 패키지 설치
사용자 인증을 사용하려면 id 관련 npm 패키지를 프로젝트에 설치해야 합니다. 프로젝트 스타일 지정의 경우 부트스트랩 사용됩니다.
터미널 표시줄에서 + 아이콘을 선택하여 새 터미널을 만듭니다. 이전 노드 터미널이 백그라운드에서 계속 실행되면 별도의 터미널 창이 열립니다.
올바른 디렉터리가 선택되었는지 확인한 후 (reactspalocal) 관련
msal
및bootstrap
패키지를 설치하려면 다음 명령을 터미널에 입력하세요.npm install @azure/msal-browser @azure/msal-react npm install react-bootstrap bootstrap
MSAL 구성에 테넌트 세부 정보 추가
authConfig.js 파일에는 인증 흐름에 대한 구성 설정이 포함되어 있으며 인증에 필요한 설정으로 MSAL.js 구성하는 데 사용됩니다.
src 폴더에서 authConfig.js 열고 다음 코드 조각을 추가합니다.
import { LogLevel } from '@azure/msal-browser'; /** * Configuration object to be passed to MSAL instance on creation. * For a full list of MSAL.js configuration parameters, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md */ export const msalConfig = { auth: { clientId: 'Enter_the_Application_Id_Here', // This is the ONLY mandatory field that you need to supply. authority: 'https://login.microsoftonline.com/Enter_the_Tenant_Info_Here', // Replace the placeholder with your tenant info redirectUri: 'http://localhost:3000/redirect', // Points to window.location.origin. You must register this URI on Microsoft Entra admin center/App Registration. postLogoutRedirectUri: '/', // Indicates the page to navigate after logout. navigateToLoginRequestUrl: false, // If "true", will navigate back to the original request location before processing the auth code response. }, cache: { cacheLocation: 'sessionStorage', // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs. storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge }, system: { loggerOptions: { loggerCallback: (level, message, containsPii) => { if (containsPii) { return; } switch (level) { case LogLevel.Error: console.error(message); return; case LogLevel.Info: console.info(message); return; case LogLevel.Verbose: console.debug(message); return; case LogLevel.Warning: console.warn(message); return; default: return; } }, }, }, }; /** * Scopes you add here will be prompted for user consent during sign-in. * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request. * For more information about OIDC scopes, visit: * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes */ export const loginRequest = { scopes: [], }; /** * An optional silentRequest object can be used to achieve silent SSO * between applications by providing a "login_hint" property. */ // export const silentRequest = { // scopes: ["openid", "profile"], // loginHint: "example@domain.net" // };
다음 값을 Microsoft Entra 관리 센터의 값으로 바꿉다.
-
clientId
- 클라이언트라고도 하는 애플리케이션의 식별자입니다.Enter_the_Application_Id_Here
등록된 애플리케이션의 개요 페이지에서 이전에 기록된 애플리케이션(클라이언트) ID 값으로 바꿉니다. -
authority
- 다음 두 부분으로 구성됩니다.
-
파일을 저장합니다.
인증 공급자 추가
msal
패키지는 애플리케이션에서 인증을 제공하는 데 사용됩니다.
msal-browser
패키지는 인증 흐름을 처리하는 데 사용되며 msal-react
패키지는 msal-browser
React와 통합하는 데 사용됩니다.
addEventCallback
사용자가 성공적으로 로그인하는 경우와 같이 인증 프로세스 중에 발생하는 이벤트를 수신 대기하는 데 사용됩니다.
setActiveAccount
메서드는 표시할 사용자의 정보를 결정하는 데 사용되는 애플리케이션의 활성 계정을 설정하는 데 사용됩니다.
src 폴더에서 index.js 열고 파일 내용을 다음 코드 조각으로 바꿔서
msal
패키지 및 부트스트랩 스타일을 사용합니다.import React from 'react'; import { createRoot } from 'react-dom/client'; import App from './App'; import { PublicClientApplication, EventType } from '@azure/msal-browser'; import { msalConfig } from './authConfig'; import 'bootstrap/dist/css/bootstrap.min.css'; import './styles/index.css'; /** * MSAL should be instantiated outside of the component tree to prevent it from being re-instantiated on re-renders. * For more, visit: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md */ const msalInstance = new PublicClientApplication(msalConfig); // Default to using the first account if no account is active on page load if (!msalInstance.getActiveAccount() && msalInstance.getAllAccounts().length > 0) { // Account selection logic is app dependent. Adjust as needed for different use cases. msalInstance.setActiveAccount(msalInstance.getActiveAccount()[0]); } // Listen for sign-in event and set active account msalInstance.addEventCallback((event) => { if (event.eventType === EventType.LOGIN_SUCCESS && event.payload.account) { const account = event.payload.account; msalInstance.setActiveAccount(account); } }); const root = createRoot(document.getElementById('root')); root.render( <App instance={msalInstance}/> );
파일을 저장합니다.
이러한 패키지에 대한 자세한 내용은 msal-browser
및 msal-react
설명서를 참조하세요.
기본 애플리케이션 구성 요소 추가
인증이 필요한 앱의 모든 부분은 MsalProvider
구성 요소에 래핑되어야 합니다.
useMsal
후크를 호출하여 PublicClientApplication
인스턴스를 가져오는 instance
변수를 설정한 다음 MsalProvider
전달합니다.
MsalProvider
구성 요소는 React의 컨텍스트 API를 통해 앱 전체에서 PublicClientApplication
인스턴스를 사용할 수 있도록 합니다.
MsalProvider
아래의 모든 구성 요소는 컨텍스트뿐만 아니라 msal-react
제공하는 모든 후크 및 구성 요소를 통해 PublicClientApplication
인스턴스에 액세스할 수 있습니다.
src 폴더에서 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;
파일을 저장합니다.
다음 단계
자습서: React 단일 페이지 앱 로그인 및 로그아웃을 위한 구성 요소 만들기