Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Berlaku untuk: Penyewa Tenaga Kerja
Penyewa Eksternal (pelajari lebih lanjut)
Dalam tutorial ini Anda akan membuat aplikasi satu halaman (SPA) React dan menyiapkannya untuk autentikasi menggunakan platform identitas Microsoft. Tutorial ini menunjukkan cara membuat React SPA menggunakan npm
, membuat file yang diperlukan untuk autentikasi dan otorisasi dan menambahkan detail penyewa Anda ke kode sumber. Aplikasi ini dapat digunakan untuk karyawan di penyewa tenaga kerja atau untuk pelanggan yang menggunakan penyewa eksternal.
Di tutorial ini, Anda akan:
- Membuat proyek React baru
- Menginstal paket yang diperlukan untuk autentikasi
- Buat struktur file Anda dan tambahkan kode ke file server
- Tambahkan rincian penyewa Anda ke file konfigurasi autentikasi
Prasyarat
- Penyewa tenaga kerja. Anda dapat menggunakan Direktori Default atau menyiapkan tenant baru.
- Daftarkan aplikasi baru di pusat admin Microsoft Entra, dikonfigurasi hanya untuk Akun di direktori organisasi ini. Lihat Mendaftarkan aplikasi untuk detail selengkapnya. Rekam nilai berikut dari halaman Gambaran Umum aplikasi untuk digunakan nanti:
- ID Aplikasi (klien)
- ID Direktori (Penyewa)
- Tambahkan URI pengalihan berikut menggunakan konfigurasi platform aplikasi satu halaman. Lihat Cara menambahkan URI pengalihan di aplikasi Anda untuk detail selengkapnya.
-
Alihkan URI:
http://localhost:3000/
.
-
Alihkan URI:
- Node.js.
- Visual Studio Code atau editor kode lainnya.
Membuat proyek React baru
Buka Visual Studio Code, pilih File >Buka Folder.... Navigasi ke dan pilih lokasi untuk membuat proyek Anda.
Buka terminal baru dengan memilih Terminal >Terminal Baru.
Jalankan perintah berikut untuk membuat proyek React baru dengan nama reactspalocal, ubah ke direktori baru dan mulai proyek React. Browser web akan terbuka dengan alamat
http://localhost:3000/
secara default. Browser tetap terbuka dan memperbarui tampilan untuk setiap perubahan yang disimpan.npx create-react-app reactspalocal cd reactspalocal npm start
Buat folder dan file tambahan untuk mencapai struktur folder berikut:
├─── 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
Menginstal paket identitas dan penyiapan awal
Identitas terkait paket npm harus diinstal dalam proyek untuk mengaktifkan autentikasi pengguna. Untuk gaya proyek, Bootstrap akan digunakan.
Di bilah Terminal, pilih ikon + untuk membuat terminal baru. Jendela terminal terpisah akan terbuka sementara terminal node sebelumnya terus berjalan di latar belakang.
Pastikan bahwa direktori yang benar dipilih (reactspalocal ) lalu masukkan yang berikut ke terminal untuk menginstal paket
msal
danbootstrap
yang relevan.npm install @azure/msal-browser @azure/msal-react npm install react-bootstrap bootstrap
Menambahkan detail penyewa Anda ke konfigurasi MSAL
File authConfig.js berisi pengaturan konfigurasi untuk alur autentikasi dan digunakan untuk mengonfigurasi MSAL.js dengan pengaturan yang diperlukan untuk autentikasi.
Di folder src, buka authConfig.js dan tambahkan cuplikan kode berikut:
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" // };
Ganti nilai berikut dengan nilai dari pusat admin Microsoft Entra.
-
clientId
- Pengidentifikasi aplikasi, juga disebut sebagai klien. GantiEnter_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 merupakan titik akhir dari 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.
-
Simpan file.
Menambahkan penyedia autentikasi
Paket msal
digunakan untuk menyediakan autentikasi dalam aplikasi. Paket msal-browser
digunakan untuk menangani alur autentikasi dan paket msal-react
digunakan untuk mengintegrasikan msal-browser
dengan React.
addEventCallback
digunakan untuk mendengarkan peristiwa yang terjadi selama proses autentikasi, seperti ketika pengguna berhasil masuk. Metode setActiveAccount
digunakan untuk mengatur akun aktif untuk aplikasi, yang digunakan untuk menentukan informasi pengguna mana yang akan ditampilkan.
Di folder src, buka index.js dan ganti konten file dengan cuplikan kode berikut untuk menggunakan paket
msal
dan gaya bootstrap: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}/> );
Simpan file.
Untuk mempelajari selengkapnya tentang paket ini, lihat dokumentasi di msal-browser
dan msal-react
.
Menambahkan komponen aplikasi utama
Semua bagian aplikasi yang memerlukan autentikasi harus dibungkus dalam komponen MsalProvider
. Anda mengatur variabel instance
yang memanggil hook useMsal
untuk mendapatkan instans PublicClientApplication
, lalu meneruskannya ke MsalProvider
. Komponen MsalProvider
membuat instans PublicClientApplication
tersedia di seluruh aplikasi Anda melalui Api Konteks React. Semua komponen di bawah MsalProvider
akan memiliki akses ke instans PublicClientApplication
melalui konteks serta semua kait dan komponen yang disediakan oleh msal-react
.
Di folder src, buka App.jsx dan ganti konten file dengan cuplikan kode berikut:
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;
Simpan file.