教程:将登录和注销流添加到 JavaScript 单页应用

在本教程中,你将配置 JavaScript 单页应用程序(SPA)进行身份验证。 在本系列 的第部分中,你创建了一个 JavaScript SPA,并为其准备好身份验证。 本教程介绍如何通过将 Microsoft身份验证库(MSAL) 组件添加到应用并生成应用的响应式用户界面(UI)来添加身份验证流。

在本教程中;

  • 添加代码到 auth.js 以处理身份验证流
  • 为应用程序生成用户界面

先决条件

将代码添加到重定向文件

身份验证流是应用程序对用户进行身份验证时执行的一系列步骤。 Auth.js 包含用于处理身份验证流的函数,包括使用重定向或弹出窗口方法登录和注销。

  1. 打开 公共/auth.js 并添加以下代码:

    // Browser check variables: If you support IE, our recommendation is to sign-in using Redirect APIs. If you are testing using Edge InPrivate mode, please add "isEdge" to the if check.
    const ua = window.navigator.userAgent;
    const msie = ua.indexOf("MSIE ");
    const msie11 = ua.indexOf("Trident/");
    const msedge = ua.indexOf("Edge/");
    const isIE = msie > 0 || msie11 > 0;
    const isEdge = msedge > 0;
    
    let signInType;
    let accountId = "";
    
    // myMSALObj instance - configuration parameters are located at authConfig.js
    const myMSALObj = new msal.PublicClientApplication(msalConfig);
    
    myMSALObj.initialize().then(() => {
        // Redirect: once login is successful and redirects with tokens, call Graph API
        myMSALObj.handleRedirectPromise().then(handleResponse).catch(err => {
            console.error(err);
        });
    })
    
    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
            showWelcomeMessage(currentAccounts[0].username);
            updateTable(currentAccounts[0]);
        }
    }
    
    function handleResponse(resp) {
        if (resp !== null) {
            accountId = resp.account.homeAccountId;
            myMSALObj.setActiveAccount(resp.account);
            showWelcomeMessage(resp.account);
        } else {
                selectAccount();
            } 
        }
    
    async function signIn(method) {
        signInType = isIE ? "redirect" : method;
        if (signInType === "popup") {
            return myMSALObj.loginPopup({
                ...loginRequest,
                redirectUri: "/redirect"
            }).then(handleResponse).catch(function (error) {
                console.log(error);
            });
        } else if (signInType === "redirect") {
            return myMSALObj.loginRedirect(loginRequest)
        }
    }
    
    function signOut(interactionType) {
        const logoutRequest = {
            account: myMSALObj.getAccountByHomeId(accountId)
        };
    
        if (interactionType === "popup") {
            myMSALObj.logoutPopup(logoutRequest).then(() => {
                window.location.reload();
            });
        } else {
            myMSALObj.logoutRedirect(logoutRequest);
        }
    }
    
    // This function can be removed if you do not need to support IE
    async function getTokenRedirect(request, account) {
        return await myMSALObj.acquireTokenSilent(request).catch(async (error) => {
            console.log("silent token acquisition fails.");
            if (error instanceof msal.InteractionRequiredAuthError) {
                // fallback to interaction when silent call fails
                console.log("acquiring token using redirect");
                myMSALObj.acquireTokenRedirect(request);
            } else {
                console.error(error);
            }
        });
    }
    
  2. 保存文件。

为应用程序生成用户界面

配置授权后,可以创建 UI 以在运行项目时与应用程序交互。 Bootstrap 用于创建响应式 UI,其中包含 登录注销 按钮。 UI 还包含一个表,该表显示令牌中的声明,稍后将在本教程中添加这些声明。

将代码添加到 index.html 文件

SPA 的主页 index.html 是应用程序启动时加载的第一页。 此页面也是用户选择“退出登录”按钮时加载的页面。 该页包括一个导航栏、一条包含用户电子邮件地址的欢迎消息,以及一个显示令牌中权限声明的表格。

  1. 打开 public/index.html 并添加以下代码片段:

     <!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>
    
     <!DOCTYPE html>
     <html lang="en">
     <head>
     <meta charset="UTF-8">
     <title>Bootstrap 5 Navbar</title>
     <!-- Bootstrap 5 CSS -->
     <link 
         href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" 
         rel="stylesheet" 
         integrity="sha384-Zenh87qX5JnK2Rl3l94faQlfdS3b8SpxyDkgOn+Y5Qu3og6JpNZnN9LfX9k8wAI5" 
         crossorigin="anonymous">
     </head>
    
     <body>
     <!-- Navbar -->
     <nav class="navbar navbar-expand-sm navbar-dark bg-primary navbarStyle">
         <a class="navbar-brand" href="/">Microsoft identity platform</a>
    
         <div class="ms-auto d-flex align-items-center">
         <!-- Dropdown group (Bootstrap 5 uses dropstart instead of dropleft) -->
         <div class="btn-group dropstart">
             <!-- Toggle button for dropdown -->
             <button
             id="signIn"
             type="button"
             class="btn btn-primary dropdown-toggle"
             data-bs-toggle="dropdown"
             aria-expanded="false"
             >
             Sign In
             </button>
    
             <!-- Dropdown menu -->
             <div class="dropdown-menu">
             <button class="dropdown-item" id="popup" onclick="signIn(this.id)">
                 Sign in using Popup
             </button>
             <button class="dropdown-item" id="redirect" onclick="signIn(this.id)">
                 Sign in using Redirect
             </button>
             </div>
         </div>
    
         <!-- Sign Out button -->
         <button class="btn btn-secondary ms-2" id="signOut" onclick="signOut()">
             Sign Out
         </button>
         </div>
     </nav>
    
    
     <br />
     <div class="container">
         <div class="row">
         <h5 id="title-div" class="card-header text-center">
             JavaScript single-page application secured with MSAL.js
         </h5>
         <br />
         <h5 id="welcome-div" class="card-header text-center d-none"></h5>
    
         <table class="table table-striped table-bordered d-none" id="table-div">
             <thead>
             <tr>
                 <th>Claim Type</th>
                 <th>Value</th>
                 <th>Description</th>
             </tr>
             </thead>
             <tbody id="table-body-div"></tbody>
         </table>
         </div>
     </div>
    
     <script 
         src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
         integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
         crossorigin="anonymous">
     </script>
    
     <!-- Bootstrap 5 JS bundle (includes Popper) -->
     <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>
    
     <!-- Your custom scripts -->
     <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="./auth.js"></script>
     </body>
     </html>
    
  2. 保存文件。

将代码添加到 ui.js 文件

若要使应用程序具有交互性,ui.js 文件用于处理应用程序的 UI 元素。 该文件包含用于在用户登录时更新用户名以及使用令牌中的声明更新表的函数。

  1. 打开 public/ui.js 并添加以下代码片段:

    // 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 showWelcomeMessage(account) {
        signInButton.classList.add('d-none');
        signOutButton.classList.remove('d-none');
        titleDiv.classList.add('d-none');
        welcomeDiv.classList.remove('d-none');
        welcomeDiv.innerHTML = `Welcome ${account.username}!`;
        updateTable(account);
    };
    
    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];
        });
    };
    
  2. 保存文件。

将代码添加到 signout.html 文件

signout.html 文件用于在用户注销应用程序时向用户显示消息。

  1. 打开 public/signout.html 并添加以下代码片段:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Microsoft Entra ID | 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/bootstrap/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>
    
  2. 保存文件。

向应用添加样式

最后,向应用程序添加一些样式,使其看起来更具吸引力。 这些样式将添加到 styles.css 文件中,可以根据需要进行自定义。

  1. 打开 public/styles.css 并添加以下代码片段:

    .navbarStyle {
        padding: .5rem 1rem !important;
    }
    
    .table-responsive-ms {
        max-height: 39rem !important;
        padding-left: 10%;
        padding-right: 10%;
    }
    
  2. 保存文件。

后续步骤