配置用于身份验证的 vanilla JavaScript 单页应用

您所在的位置:网站首页 一次性重命名 配置用于身份验证的 vanilla JavaScript 单页应用

配置用于身份验证的 vanilla JavaScript 单页应用

#配置用于身份验证的 vanilla JavaScript 单页应用| 来源: 网络整理| 查看: 265

你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。

创建用于身份验证和授权的组件 项目 05/24/2023

在上一篇文章中,你创建了一个 vanilla JavaScript (JS) 单页应用程序 (SPA) 和一个服务器来托管它。 在本文中,你将配置应用程序以对用户进行身份验证并授权用户访问受保护的资源。 身份验证和授权由适用于 JavaScript 的 Microsoft 身份验证库 (MSAL.js) 处理。 该库用于对用户进行身份验证,并从 Azure Active Directory (AD) 为客户获取访问令牌。

先决条件 完成准备用于身份验证的单页应用程序中的先决条件和步骤。 创建身份验证配置文件

应用程序使用隐式授权流对用户进行身份验证。 隐式授权流是基于浏览器的流,不需要后端服务器。 该流将用户重定向到登录页,用户在其中登录并同意应用程序请求的权限。 authConfig.js 的用途是配置身份验证流。

在 IDE 中,创建一个新文件夹并将其命名为 public

在 public 文件夹中,创建一个新文件并将其命名为 authConfig.js。

打开 authConfig.js 并添加以下代码片段:

/** * 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 */ const msalConfig = { auth: { clientId: 'Enter_the_Application_Id_Here', // This is the ONLY mandatory field that you need to supply. authority: 'https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/', // Replace "Enter_the_Tenant_Subdomain_Here" with your tenant subdomain redirectUri: '/', // You must register this URI on Azure Portal/App Registration. Defaults to window.location.href e.g. http://localhost:3000/ navigateToLoginRequestUrl: true, // 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. storeAuthStateInCookie: false, // set this to true if you have to support IE }, system: { loggerOptions: { loggerCallback: (level, message, containsPii) => { if (containsPii) { return; } switch (level) { case msal.LogLevel.Error: console.error(message); return; case msal.LogLevel.Info: console.info(message); return; case msal.LogLevel.Verbose: console.debug(message); return; case msal.LogLevel.Warning: console.warn(message); return; } }, }, }, }; /** * An optional silentRequest object can be used to achieve silent SSO * between applications by providing a "login_hint" property. */ // const silentRequest = { // scopes: ["openid", "profile"], // loginHint: "[email protected]" // }; // exporting config object for jest if (typeof exports !== 'undefined') { module.exports = { msalConfig: msalConfig, loginRequest: loginRequest, }; }

找到 Enter_the_Application_Id_Here 值并将其替换为你在 Microsoft Entra 管理中心注册的应用的应用程序 ID (clientId)。

在“颁发机构”中,找到 Enter_the_Tenant_Subdomain_Here 并将其替换为租户的子域。 例如,如果租户主域为 [email protected],则应输入的值为 casyjensen。

保存文件。

创建重定向文件

需要重定向文件来处理来自登录页的响应。 重定向文件用于从 URL 片段中提取访问令牌,并用它来调用受保护的 API。

在 public 文件夹中,创建一个新文件并将其命名为 authRedirect.js。

打开 authRedirect.js 并添加以下代码片段:

// 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) { 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) { welcomeUser(response.account.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); }

保存文件。

创建 authPopup.js 文件

当用户使用弹出窗口登录时,应用程序使用 authPopup.js 来处理身份验证流。 如果用户已登录,而应用程序需要获取另一资源的访问令牌时,则使用弹出窗口。

在 public 文件夹中,创建一个新文件并将其命名为 authPopup.js。

打开 authPopup.js 并添加以下代码片段:

// 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();

保存文件。

后续步骤

配置单页应用程序用户界面和登录



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3