快速上手:在单页应用 (SPA) 中让用户登录并调用 Microsoft Graph API

适用于:带白色勾号的绿色圆圈。 员工租户 带白色勾号的绿色圆圈。 外部租户(了解详细信息

在本快速入门中,你将使用示例单页应用(SPA)来演示如何使用 授权代码流 和代码交换证明密钥(PKCE)登录用户,并调用Microsoft图形 API。 此示例使用 Microsoft身份验证库 来处理身份验证。

先决条件

  • 具有活动订阅的 Azure 帐户。 如果您还没有帐户,请免费创建一个帐户
  • Azure 帐户必须拥有管理应用程序的权限。 以下任何Microsoft Entra 角色都包含所需的权限:
    • 应用程序管理员
    • 应用程序开发人员
  • 工作人员租户。 可以使用默认目录或 设置新租户
  • Visual Studio Code 或其他代码编辑器。

克隆或下载示例应用程序

若要获取示例应用程序,可以从 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",
             // WORKFORCE TENANT
             authority: "https://login.microsoftonline.com/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://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview#openid-connect-scopes
     */
    const loginRequest = {
        scopes: ["User.Read"],
    };
    
    /**
     * 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. 若要启动服务器,请从项目目录中运行以下命令:

    cd vanillajs-spa/App
    npm install
    npm start
    
  2. 复制终端中显示的 https URL,例如 https://localhost:3000,并将其粘贴到浏览器中。 建议使用专用或隐身浏览器会话。

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

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

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

先决条件

克隆或下载示例 SPA

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

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

    git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git
    
  • 下载示例。 将其解压缩到名称长度少于 260 个字符的文件路径。

配置示例 SPA

  1. 打开 App/public/authConfig.js,并将以下内容替换为从 Microsoft Entra 管理中心获取的值:

    • 查找 Enter_the_Application_Id_Here 并将其替换为之前注册的应用的应用程序(客户端)ID。
    • Enter_the_Tenant_Subdomain_Here 并将其替换为 Directory (tenant) 子域。 例如,如果租户主域名是 contoso.onmicrosoft.com,请使用 contoso。 如果没有租户名称,请了解如何读取租户详细信息
  2. 保存文件。

运行项目并登录

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

    cd 1-Authentication\0-sign-in-vanillajs\App
    npm install
    npm start
    
  2. 复制终端中显示的 https URL,例如 https://localhost:3000,并将其粘贴到浏览器中。 建议使用专用或隐身浏览器会话。

  3. 使用注册到租户的帐户登录。

  4. 将显示以下屏幕截图,指示已登录到应用程序,并从 Microsoft Graph API 访问配置文件详细信息。

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

从应用程序注销

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

此时会显示一条消息,指示你已注销。现在可以关闭浏览器窗口。