快速上手:在单页应用 (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: {
    
            // WORKFORCE TENANT
            authority: "https://login.partner.microsoftonline.cn/Enter_the_Tenant_Info_Here", //  Replace the placeholder with your tenant info
            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: ["https://microsoftgraph.chinacloudapi.cn/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 应用的屏幕截图。