자습서: React 단일 페이지 애플리케이션 만들기 및 인증 준비

등록이 완료되면 IDE(통합 개발 환경)를 사용하여 React 프로젝트를 만들 수 있습니다. 이 자습서에서는 npm을(를) 사용하여 단일 페이지 React 애플리케이션을 만들고 인증 및 권한 부여에 필요한 파일을 만드는 방법을 보여 줍니다.

이 자습서에서:

  • 새 React 프로젝트 만들기
  • 애플리케이션에 대한 설정 구성
  • ID 및 부트스트랩 패키지 설치
  • 애플리케이션에 인증 코드 추가

필수 조건

  • 자습서: 애플리케이션 등록의 필수 구성 요소 및 단계를 완료합니다.
  • React 애플리케이션을 지원하는 모든 IDE를 사용할 수 있지만 이 자습서에는 다음 Visual Studio IDE가 사용됩니다. 다운로드 페이지에서 다운로드할 수 있습니다. macOS 사용자의 경우 Visual Studio Code를 사용하는 것이 좋습니다.
    • Visual Studio 2022
    • Visual Studio Code
  • Node.js

새 React 프로젝트 만들기

다음 탭을 사용하여 IDE 내에 React 프로젝트를 만듭니다.

  1. Visual Studio를 열고 새 프로젝트 만들기를 선택합니다.

  2. 독립 실행형 JavaScript React 프로젝트 템플릿을 검색하여 선택한 다음, 다음을 선택합니다.

  3. 프로젝트의 이름(예: reactspalocal)을 입력합니다.

  4. 프로젝트의 위치를 선택하거나 기본 옵션을 적용한 다음, 다음을 선택합니다.

  5. 추가 정보에서 만들기를 선택합니다.

  6. 도구 모음에서 디버깅하지 않고 시작을 선택하여 애플리케이션을 시작합니다. 웹 브라우저는 기본적으로 주소 http://localhost:3000/으로 열립니다. 브라우저는 열린 상태로 유지되며 저장된 모든 변경 내용에 대해 다시 렌더링됩니다.

  7. 다음과 같은 폴더 구조를 얻으려면 추가 폴더와 파일을 만듭니다.

    ├─── public
    │   └─── index.html
    └───src
        ├─── components
        │   └─── PageLayout.jsx
        │   └─── ProfileData.jsx
        │   └─── SignInButton.jsx
        │   └─── SignOutButton.jsx
        └── App.css
        └── App.jsx
        └── authConfig.js
        └── graph.js
        └── index.css
        └── index.js
    

ID 및 부트스트랩 패키지 설치

사용자 인증을 사용하도록 설정하려면 프로젝트에 ID 관련 npm 패키지를 설치해야 합니다. 프로젝트 스타일 지정의 경우 부트스트랩이 사용됩니다.

  1. 솔루션 탐색기에서 npm 옵션을 마우스 오른쪽 단추로 클릭하고 새 npm 패키지 설치를 선택합니다.
  2. @azure/MSAL 브라우저를 검색한 다음 패키지 설치를 선택합니다. @azure/MSAL 반응에 대해 반복합니다.
  3. react-bootstrap을 검색하고 설치합니다.
  4. 닫기를 선택합니다.

이러한 패키지에 대한 자세한 내용은 다음의 msal-react설명서를 msal-browser 참조하세요.

인증 구성 파일 만들기

  1. src 폴더에서 authConfig.js를 열고 다음 코드 조각을 추가합니다.

    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    
    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",
            authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here",
            redirectUri: "http://localhost:3000",
        },
        cache: {
            cacheLocation: "sessionStorage", // This configures where your cache will be stored
            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: ["User.Read"]
    };
    
    /**
     * Add here the scopes to request when obtaining an access token for MS Graph API. For more information, see:
     * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
     */
    export const graphConfig = {
        graphMeEndpoint: "https://graph.microsoft.com/v1.0/me",
    };
    
  2. 다음 값을 Microsoft Entra 관리 센터의 값으로 바꿉니다.

    • clientId - 클라이언트라고도 하는 애플리케이션의 식별자입니다. Enter_the_Application_Id_Here를 등록된 애플리케이션의 개요 페이지에서 앞서 기록한 애플리케이션(클라이언트) ID 값으로 바꿉니다.
    • authority - 이 작업은 다음 두 부분으로 구성됩니다.
      • 인스턴스는 클라우드 공급자의 엔드포인트입니다. 국가별 클라우드에서 사용 가능한 다양한 엔드포인트를 확인합니다.
      • 테넌트 ID는 애플리케이션이 등록된 테넌트 식별자입니다. Enter_the_Tenant_Info_Here 등록된 애플리케이션의 개요 페이지에서 이전에 기록된 디렉터리(테넌트) ID 값으로 바꿉니다.
  3. 파일을 저장합니다.

인증 공급자를 포함하도록 index.js 수정

인증이 필요한 앱의 모든 부분을 MsalProvider 구성 요소에 래핑해야 합니다. PublicClientApplication을 인스턴스화한 다음, MsalProvider에 전달합니다.

  1. src 폴더에서 index.js를 열고 파일 콘텐츠를 다음 코드 조각으로 바꿔 msal 패키지와 부트스트랩 스타일을 사용합니다.

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    
    import { PublicClientApplication } from '@azure/msal-browser';
    import { MsalProvider } from '@azure/msal-react';
    import { msalConfig } from './authConfig';
    
    // Bootstrap components
    import 'bootstrap/dist/css/bootstrap.min.css';
    
    const msalInstance = new PublicClientApplication(msalConfig);
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    
    /**
     * We recommend wrapping most or all of your components in the MsalProvider component. It's best to render the MsalProvider as close to the root as possible.
     */
     root.render(
      <React.StrictMode>
          <MsalProvider instance={msalInstance}>
              <App />
          </MsalProvider>
      </React.StrictMode>
    );
    
  2. 파일을 저장합니다.

다음 단계