Kurz: Přidání toků přihlašování a odhlášení do JavaScript SPA
V tomto kurzu nakonfigurujete jednostránkové aplikace JavaScriptu (SPA) pro ověřování. V 1. části této sériejste vytvořili JavaScript SPA a připravili ho na ověření. V tomto kurzu se dozvíte, jak přidat toky ověřování přidáním komponent knihovny MSAL (Microsoft Authentication Library) do vaší aplikace a vytvoření responzivního uživatelského rozhraní (UI) pro vaši aplikaci.
V tomto kurzu;
- Přidejte kód do authRedirect.js pro zpracování procesu ověřování
- Přidejte kód do authPopup.js k provedení ověřovacího procesu.
- Vytvoření uživatelského rozhraní pro aplikaci
Požadavky
Přidání kódu do souboru přesměrování
K zpracování odpovědi z přihlašovací stránky se vyžaduje soubor přesměrování. Slouží k extrakci přístupového tokenu z fragmentu adresy URL a k volání chráněného rozhraní API. Používá se také k zachycení chyb, ke kterým dochází během procesu ověřování.
Otevřete public/authRedirect.js a přidejte následující kód:
// Create the main myMSALObj instance // configuration parameters are located at authConfig.js const myMSALObj = new msal.PublicClientApplication(msalConfig); let username = ""; /** * A promise handler needs to be registered for handling the * response returned from redirect flow. For more information, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/initialization.md#redirect-apis */ myMSALObj.handleRedirectPromise() .then(handleResponse) .catch((error) => { console.error(error); }); function selectAccount() { /** * See here for more info on account retrieval: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md */ const currentAccounts = myMSALObj.getAllAccounts(); if (!currentAccounts) { return; } else if (currentAccounts.length > 1) { // Add your account choosing logic here console.warn("Multiple accounts detected."); } else if (currentAccounts.length === 1) { username = currentAccounts[0].username welcomeUser(currentAccounts[0].username); updateTable(currentAccounts[0]); } } function handleResponse(response) { /** * To see the full list of response object properties, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#response */ if (response !== null) { username = response.account.username welcomeUser(username); updateTable(response.account); } else { selectAccount(); } } function signIn() { /** * You can pass a custom request object below. This will override the initial configuration. For more information, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request */ myMSALObj.loginRedirect(loginRequest); } function signOut() { /** * You can pass a custom request object below. This will override the initial configuration. For more information, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request */ // Choose which account to logout from by passing a username. const logoutRequest = { account: myMSALObj.getAccountByUsername(username), postLogoutRedirectUri: '/signout', // remove this line if you would like navigate to index page after logout. }; myMSALObj.logoutRedirect(logoutRequest); }
Uložte soubor.
Přidání kódu do souboru authPopup.js
Aplikace používá authPopup.js ke zpracování toku ověřování, když se uživatel přihlásí pomocí automaticky otevíraných oken. Automaticky otevírané okno se používá, když je uživatel již přihlášený a aplikace potřebuje získat přístupový token pro jiný prostředek.
Otevřete public/authPopup.js a přidejte následující kód:
// Create the main myMSALObj instance // configuration parameters are located at authConfig.js const myMSALObj = new msal.PublicClientApplication(msalConfig); let username = ""; function selectAccount () { /** * See here for more info on account retrieval: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md */ const currentAccounts = myMSALObj.getAllAccounts(); if (!currentAccounts || currentAccounts.length < 1) { return; } else if (currentAccounts.length > 1) { // Add your account choosing logic here console.warn("Multiple accounts detected."); } else if (currentAccounts.length === 1) { username = currentAccounts[0].username welcomeUser(currentAccounts[0].username); updateTable(currentAccounts[0]); } } function handleResponse(response) { /** * To see the full list of response object properties, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#response */ if (response !== null) { username = response.account.username welcomeUser(username); updateTable(response.account); } else { selectAccount(); } } function signIn() { /** * You can pass a custom request object below. This will override the initial configuration. For more information, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request */ myMSALObj.loginPopup(loginRequest) .then(handleResponse) .catch(error => { console.error(error); }); } function signOut() { /** * You can pass a custom request object below. This will override the initial configuration. For more information, visit: * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request */ // Choose which account to logout from by passing a username. const logoutRequest = { account: myMSALObj.getAccountByUsername(username), mainWindowRedirectUri: '/signout' }; myMSALObj.logoutPopup(logoutRequest); } selectAccount();
Uložte soubor.
Vytvoření uživatelského rozhraní pro aplikaci
Po nakonfigurování autorizace je možné vytvořit uživatelské rozhraní pro interakci s aplikací při spuštění projektu. Bootstrap se používá k vytvoření responzivního uživatelského rozhraní, které obsahuje tlačítko přihlášení a tlačítko odhlášení. Uživatelské rozhraní obsahuje také tabulku, která zobrazuje nároky z tokenu, které budou přidány později v tutoriálu.
Přidání kódu do souboru index.html
Hlavní stránka SPA, index.html, je první stránka, která se načte při spuštění aplikace. Je to také stránka, která se načte, když uživatel vybere tlačítko Odhlásit se. Stránka obsahuje navigační panel, uvítací zprávu s e-mailem uživatelů a tabulku, která zobrazuje deklarace identity z tokenu.
Otevřete public/index.html a přidejte následující fragment kódu:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no"> <title>Microsoft identity platform</title> <link rel="SHORTCUT ICON" href="./favicon.svg" type="image/x-icon"> <link rel="stylesheet" href="./styles.css"> <!-- adding Bootstrap 5 for UI components --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"> <!-- msal.min.js can be used in the place of msal-browser.js --> <script src="/msal-browser.min.js"></script> </head> <body> <nav class="navbar navbar-expand-sm navbar-dark bg-primary navbarStyle"> <a class="navbar-brand" href="/">Microsoft identity platform</a> <div class="navbar-collapse justify-content-end"> <button type="button" id="signIn" class="btn btn-secondary" onclick="signIn()">Sign-in</button> <button type="button" id="signOut" class="btn btn-success d-none" onclick="signOut()">Sign-out</button> </div> </nav> <br> <h5 id="title-div" class="card-header text-center">JavaScript single-page application secured with MSAL.js </h5> <h5 id="welcome-div" class="card-header text-center d-none"></h5> <br> <div class="table-responsive-ms" id="table"> <table id="table-div" class="table table-striped d-none"> <thead id="table-head-div"> <tr> <th>Claim Type</th> <th>Value</th> <th>Description</th> </tr> </thead> <tbody id="table-body-div"> </tbody> </table> </div> <!-- importing bootstrap.js and supporting js libraries --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script> <!-- importing app scripts (load order is important) --> <script type="text/javascript" src="./authConfig.js"></script> <script type="text/javascript" src="./ui.js"></script> <script type="text/javascript" src="./claimUtils.js"></script> <!-- <script type="text/javascript" src="./authRedirect.js"></script> --> <!-- uncomment the above line and comment the line below if you would like to use the redirect flow --> <script type="text/javascript" src="./authPopup.js"></script> </body> </html>
Uložte soubor.
Přidání kódu do souboru ui.js
Aby byla vaše aplikace interaktivní, ui.js soubor slouží ke zpracování prvků uživatelského rozhraní aplikace. Soubor obsahuje funkce, které slouží k aktualizaci jména uživatele při přihlášení a aktualizaci tabulky deklaracemi identity z tokenu.
Otevřete public/ui.js a přidejte následující fragment kódu:
// Select DOM elements to work with const signInButton = document.getElementById('signIn'); const signOutButton = document.getElementById('signOut'); const titleDiv = document.getElementById('title-div'); const welcomeDiv = document.getElementById('welcome-div'); const tableDiv = document.getElementById('table-div'); const tableBody = document.getElementById('table-body-div'); function welcomeUser(username) { signInButton.classList.add('d-none'); signOutButton.classList.remove('d-none'); titleDiv.classList.add('d-none'); welcomeDiv.classList.remove('d-none'); welcomeDiv.innerHTML = `Welcome ${username}!`; }; function updateTable(account) { tableDiv.classList.remove('d-none'); const tokenClaims = createClaimsTable(account.idTokenClaims); Object.keys(tokenClaims).forEach((key) => { let row = tableBody.insertRow(0); let cell1 = row.insertCell(0); let cell2 = row.insertCell(1); let cell3 = row.insertCell(2); cell1.innerHTML = tokenClaims[key][0]; cell2.innerHTML = tokenClaims[key][1]; cell3.innerHTML = tokenClaims[key][2]; }); };
Uložte soubor.
Přidání kódu do souboru signout.html
Soubor signout.html slouží k zobrazení zprávy uživateli při odhlášení z aplikace.
Otevřete public/signout.html a přidejte následující fragment kódu:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript SPA</title> <link rel="SHORTCUT ICON" href="./favicon.svg" type="image/x-icon"> <!-- adding Bootstrap 4 for UI components --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/boot8strap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <div class="jumbotron" style="margin: 10%"> <h1>Goodbye!</h1> <p>You have signed out and your cache has been cleared.</p> <a class="btn btn-primary" href="/" role="button">Take me back</a> </div> </body> </html>
Uložte soubor.
Přidání stylů do aplikace
Nakonec do aplikace přidejte některé styly, aby vypadala působivěji. Styly se přidají do souboru styles.css a dají se přizpůsobit tak, aby vyhovovaly vašim potřebám.
Otevřete public/styles.css a přidejte následující fragment kódu:
.navbarStyle { padding: .5rem 1rem !important; } .table-responsive-ms { max-height: 39rem !important; padding-left: 10%; padding-right: 10%; }
Uložte soubor.