快速入门:在单页应用 (SPA) 中登录用户,并使用 JavaScript 调用 Microsoft Graph API

本快速入门使用示例 JavaScript (JS) 单页应用 (SPA) 向你展示如何使用授权代码流和代码交换证明密钥 (PKCE) 让用户登录,以及如何调用 Microsoft Graph API。 此示例使用适用于 JavaScript 的 Microsoft 身份验证库来处理身份验证。

先决条件

注册应用程序和记录标识符

若要完成注册,请为应用程序命名,指定支持的帐户类型并添加重定向 URI。 注册后,应用程序“概述”窗格将显示应用程序源代码中所需的标识符。

  1. 登录到 Microsoft Entra 管理中心

  2. 如果你有权访问多个租户,请使用顶部菜单中的“设置”图标 ,通过“目录 + 订阅”菜单切换到你希望在其中注册应用程序的租户。

  3. 浏览至“标识”>“应用程序”>“应用注册”,然后选择“新建注册”。

  4. 输入应用程序的“名称”,例如“identity-client-spa”

  5. 对于“支持的帐户类型”设置,请选择“仅限此组织目录中的帐户”。 要了解不同帐户类型的信息,请选择“帮我选择”选项。

  6. 选择“注册”。

    屏幕截图显示如何在 Azure 门户中输入名称并选择帐户类型。

  7. 注册完成后,将显示应用程序的“概述”窗格。 记录要在应用程序源代码中使用的目录(租户)ID 和应用程序(客户端)ID。

    屏幕截图显示 Azure 门户的“概述”页面上的标识符值。

    注意

    可以通过参照修改应用程序支持的帐户来更改支持的帐户类型。

添加平台重定向 URI

若要为应用注册指定应用类型,请执行以下步骤:

  1. 在“管理”下,选择“身份验证”。
  2. 在“平台配置”页上,选择“添加平台”,然后选择“SPA”选项。
  3. 对于“重定向 URI”,请输入 http://localhost:3000
  4. 选择“配置”以保存更改。

克隆或下载示例应用程序

若要获取示例应用程序,可以从 GitHub 克隆它或将其下载为 .zip 文件。

  • 若要克隆示例,请打开命令提示符并导航到要创建项目的位置,然后输入以下命令:

    git clone https://github.com/Azure-Samples/ms-identity-docs-code-javascript.git
    
  • 下载 .zip 文件。 将其提取到名称长度小于 260 个字符的文件路径。

配置项目

  1. 在 IDE 中,打开包含示例的项目文件夹 ms-identity-docs-code-javascript。

  2. 打开 vanillajs-spa/App/public/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
             // WORKFORCE TENANT
             authority: "https://login.partner.microsoftonline.cn/Enter_the_Tenant_Info_Here", //  Replace the placeholder with your tenant info
             // EXTERNAL TENANT
             // authority: "https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/", // Replace the placeholder with your tenant subdomain
             redirectUri: '/', // You must register this URI on 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;
                     }
                 },
             },
         },
     };
    
     /**
      * 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.azure.cn/entra/identity-platform/permissions-consent-overview#openid-connect-scopes
      */
     const loginRequest = {
         scopes: [],
     };
    
     /**
      * 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: "example@domain.net"
     // };
    
     // exporting config object for jest
     if (typeof exports !== 'undefined') {
         module.exports = {
             msalConfig: msalConfig,
             loginRequest: loginRequest,
         };
     }
    
    • clientId - 应用程序的标识符,也称为客户端。 将引号中的文本替换为先前记录的应用程序(客户端)ID 值
    • authority - 颁发机构是一个 URL,表示 MSAL 可从中请求令牌的目录。 请将“Enter_the_Tenant_Info_Here”替换为先前记录的“目录(租户)ID”值。
    • redirectUri:应用程序的重定向 URI。 如有必要,请将引号中的文本替换为先前记录的重定向 URI。

运行应用程序并登录

使用 Node.js 在 Web 服务器中运行项目:

  1. 若要启动服务器,请从项目目录中运行以下命令:

    npm install
    npm start
    
  2. 复制终端中显示的 https URL(例如 https://localhost:3000),并将其粘贴到浏览器中。 建议使用私密浏览器或无痕浏览器会话。

  3. 按照步骤操作并输入必要的详细信息以使用 Microsoft 帐户登录。 系统会要求你提供电子邮件地址,以便向你发送一次性密码。 出现提示时输入代码。

  4. 该应用程序将请求维持你对已授权访问的数据的访问权限,以及让你登录并读取个人资料的权限。 选择“接受”。 将显示以下屏幕截图,表明你已登录应用程序且已从 Microsoft Graph API 访问个人资料详细信息。

    描述 API 调用结果的 JavaScript 应用的屏幕截图。

退出登录应用程序

  1. 在页面右上角找到“退出登录”按钮,然后选中它
  2. 系统将提示你选择要退出登录的帐户。 选择用于登录的帐户。

此时会显示一条消息,表明你已退出登录。现在可以关闭浏览器窗口。