Tutorial: Membuat aplikasi satu halaman React dan menyiapkannya untuk autentikasi

Setelah pendaftaran selesai, proyek React dapat dibuat menggunakan lingkungan pengembangan terintegrasi (IDE). Tutorial ini menunjukkan cara membuat aplikasi React satu halaman menggunakan npm dan membuat file yang diperlukan untuk autentikasi dan otorisasi.

Dalam tutorial ini:

  • Membuat proyek React baru
  • Mengonfigurasi pengaturan untuk aplikasi
  • Menginstal paket identitas dan bootstrap
  • Menambahkan kode autentikasi ke aplikasi

Prasyarat

  • Penyelesaian prasyarat dan langkah-langkah dalam Tutorial: Mendaftarkan aplikasi.
  • Meskipun IDE apa pun yang mendukung aplikasi React dapat digunakan, ID Visual Studio berikut digunakan untuk tutorial ini. Mereka dapat diunduh dari halaman Unduhan . Untuk pengguna macOS, disarankan untuk menggunakan Visual Studio Code.
    • Visual Studio 2022
    • Visual Studio Code
  • Node.js.

Membuat proyek React baru

Gunakan tab berikut untuk membuat proyek React dalam IDE.

  1. Buka Visual Studio, lalu pilih Buat proyek baru.

  2. Cari dan pilih templat Proyek React JavaScript Mandiri, lalu pilih Berikutnya.

  3. Masukkan nama untuk proyek, seperti reactspalocal.

  4. Pilih lokasi untuk proyek atau terima opsi default, lalu pilih Berikutnya.

  5. Di Informasi tambahan, pilih Buat.

  6. Dari toolbar, pilih Mulai Tanpa Penelusuran Kesalahan untuk meluncurkan aplikasi. Browser web akan terbuka dengan alamat http://localhost:3000/ secara default. Browser tetap terbuka dan dirender ulang untuk setiap perubahan yang disimpan.

  7. Buat folder dan file tambahan untuk mencapai struktur folder berikut:

    ├─── 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
    

Menginstal paket identitas dan bootstrap

Paket npm terkait identitas harus diinstal dalam proyek untuk mengaktifkan autentikasi pengguna. Untuk gaya proyek, Bootstrap akan digunakan.

  1. Di Penjelajah Solusi, klik kanan opsi npm dan pilih Instal paket npm baru.
  2. Cari browser @azure/MSAL, lalu pilih Instal Paket. Ulangi untuk @azure/MSAL-react.
  3. Cari dan instal react-bootstrap.
  4. Pilih Tutup.

Untuk mempelajari selengkapnya tentang paket ini, lihat dokumentasi di msal-browser dan msal-react.

Membuat file konfigurasi autentikasi

  1. Di folder src, buka authConfig.js dan tambahkan cuplikan kode berikut:

    /*
     * 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. Ganti nilai berikut dengan nilai dari pusat admin Microsoft Entra.

    • clientId - Pengidentifikasi aplikasi, juga disebut sebagai klien. Ganti Enter_the_Application_Id_Here dengan nilai ID Aplikasi (klien) yang direkam sebelumnya dari halaman gambaran umum aplikasi terdaftar.
    • authority - Ini terdiri dari dua bagian:
      • Instans adalah titik akhir penyedia cloud. Periksa dengan berbagai titik akhir yang tersedia di cloud Nasional.
      • ID Penyewa adalah pengidentifikasi penyewa tempat aplikasi terdaftar. Ganti Enter_the_Tenant_Info_Here dengan nilai ID Direktori (penyewa) yang direkam sebelumnya dari halaman gambaran umum aplikasi terdaftar.
  3. Simpan file.

Ubah index.js untuk menyertakan penyedia autentikasi

Semua bagian aplikasi yang memerlukan autentikasi harus dibungkus dalam MsalProvider komponen. Anda membuat instans PublicClientApplication lalu meneruskannya ke MsalProvider.

  1. Di folder src, buka index.js dan ganti konten file dengan cuplikan kode berikut untuk menggunakan msal paket dan gaya bootstrap:

    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. Simpan file.

Langkah berikutnya