使用 MSAL.js 初始化客户端应用程序Initialize client applications using MSAL.js

本文介绍如何使用用户代理应用程序的实例初始化适用于 JavaScript 的 Microsoft 身份验证库 (MSAL.js)。This article describes initializing Microsoft Authentication Library for JavaScript (MSAL.js) with an instance of a user-agent application.

该用户代理应用程序是某种形式的公共客户端应用程序,其中的客户端代码在 Web 浏览器等用户代理中执行。The user-agent application is a form of public client application in which the client code is executed in a user-agent such as a web browser. 此类客户端不存储机密,因为浏览器上下文可公开访问。Such clients do not store secrets because the browser context is openly accessible.

若要详细了解客户端应用程序类型和应用程序配置选项,请参阅 MSAL 中的公共和机密客户端应用To learn more about the client application types and application configuration options, see Public and confidential client apps in MSAL.

先决条件Prerequisites

在初始化应用程序之前,首先需要在 Azure 门户中注册该应用程序,从而在应用程序和 Microsoft 标识平台之间建立信任关系。Before initializing an application, you first need to register it with the Azure portal, establishing a trust relationship between your application and the Microsoft identity platform.

注册应用后,你需要以下部分值或所有值,这些可以在 Azure 门户中找到。After registering your app, you'll need some or all of the following values that can be found in the Azure portal.

Value 必选Required 说明Description
应用程序(客户端)IDApplication (client) ID 必选Required 在 Microsoft 标识平台中唯一标识你的应用程序的 GUID。A GUID that uniquely identifies your application within the Microsoft identity platform.
颁发机构Authority 可选Optional 标识提供者 URL(实例)和应用程序的登录受众 。The identity provider URL (the instance) and the sign-in audience for your application. 实例和登录受众连接起来后就组成了颁发机构。The instance and sign-in audience, when concatenated, make up the authority.
目录(租户)IDDirectory (tenant) ID 可选Optional 如果构建专用于组织的业务线应用程序(通常称为单租户应用程序),请指定此项。Specify this if you're building a line-of-business application solely for your organization, often referred to as a single-tenant application.
重定向 URIRedirect URI 可选Optional 如果要构建 Web 应用,redirectUri 指定标识提供者(Microsoft 标识平台)应在何处返回其已颁发的安全令牌。If you're building a web app, the redirectUri specifies where the identity provider (the Microsoft identity platform) should return the security tokens it has issued.

初始化 MSAL.js 2.x 应用Initialize MSAL.js 2.x apps

通过使用配置对象实例化 PublicClientApplication 来初始化 MSAL 身份验证上下文。Initialize the MSAL authentication context by instantiating a PublicClientApplication with a Configuration object. 所需的最低配置属性是应用程序的 clientID,在 Azure 门户中应用注册的“概述”页上显示为“应用程序(客户端) ID” 。The minimum required configuration property is the clientID of your application, shown as the Application (client) ID on the Overview page of the app registration in the Azure portal.

下面是一个示例配置对象和 PublicClientApplication 的实例化:Here's an example configuration object and instantiation of a PublicClientApplication:

const msalConfig = {
    auth: {
        clientId: "11111111-1111-1111-111111111111",
        authority: "https://login.partner.microsoftonline.cn/common",
        knownAuthorities: [],
        redirectUri: "https://localhost:3001",
        postLogoutRedirectUri: "https://localhost:3001/logout",
        navigateToLoginRequestUrl: true
    },
    cache: {
        cacheLocation: "sessionStorage",
        storeAuthStateInCookie: false
    },
    system: {
        loggerOptions: {
            loggerCallback: (level: LogLevel, message: string, containsPii: boolean): void => {
                if (containsPii) {
                    return;
                }
                switch (level) {
                    case LogLevel.Error:
                        console.error(message);
                        return;
                    case LogLevel.Info:
                        console.info(message);
                        return;
                    case LogLevel.Verbose:
                        console.debug(message);
                        return;
                    case LogLevel.Warning:
                        console.warn(message);
                        return;
                }
            },
            piiLoggingEnabled: false
        },
        windowHashTimeout: 60000,
        iframeHashTimeout: 6000,
        loadFrameTimeout: 0
    }
};

// Create an instance of PublicClientApplication
const msalInstance = new PublicClientApplication(msalConfig);

// Handle the redirect flows
msalInstance.handleRedirectPromise().then((tokenResponse) => {
    // Handle redirect response
}).catch((error) => {
    // Handle redirect error
});

handleRedirectPromise

当应用程序使用重定向流时,调用 handleRedirectPromiseInvoke handleRedirectPromise when your application uses the redirect flows. 使用重定向流时,应在每次加载页面时运行 handleRedirectPromiseWhen using the redirect flows, handleRedirectPromise should be run on every page load.

这个承诺有三种可能的结果:There are three possible outcomes from the promise:

  • .then 被调用且 tokenResponse 为 truthy:应用程序从成功的重定向操作返回。.then is invoked and tokenResponse is truthy: The application is returning from a redirect operation that was successful.
  • .then 被调用且 tokenResponse 为 falsey (null):应用程序未从重定向操作返回。.then is invoked and tokenResponse is falsey (null): The application is not returning from a redirect operation.
  • .catch 被调用:应用程序从重定向操作返回,但出现错误。.catch is invoked: The application is returning from a redirect operation and there was an error.

初始化 MSAL.js 1.x 应用Initialize MSAL.js 1.x apps

通过使用配置对象实例化 UserAgentApplication 来初始化 MSAL 1.x 身份验证上下文。Initialize the MSAL 1.x authentication context by instantiating a UserAgentApplication with a configuration object. 所需的最低配置属性是应用程序的 clientID,在 Azure 门户中应用注册的“概述”页上显示为“应用程序(客户端) ID” 。The minimum required configuration property is the clientID of your application, shown as the Application (client) ID on the Overview page of the app registration in the Azure portal.

对于 MSAL.js 1.2.x 或更早版本中使用重定向流(loginRedirectacquireTokenRedirect)的身份验证方法,必须通过 handleRedirectCallback() 方法显式注册一个返回成功或错误结果的回调。For authentication methods with redirect flows (loginRedirect and acquireTokenRedirect) in MSAL.js 1.2.x or earlier, you must explicitly register a callback for success or error through the handleRedirectCallback() method. 在 MSAL.js 1.2.x 和更早版本中,必须显式注册回调,因为重定向流不会像具有弹出体验的方法那样返回承诺。Explicitly registering the callback is required in MSAL.js 1.2.x and earlier because redirect flows do not return promises like the methods with a pop-up experience do. 在 MSAL.js 版本 1.3.x 和更高版本中注册回调是可选操作。Registering the callback is optional in MSAL.js version 1.3.x and later.

// Configuration object constructed
const msalConfig = {
    auth: {
        clientId: "11111111-1111-1111-111111111111"
    }
}

// Create UserAgentApplication instance
const msalInstance = new UserAgentApplication(msalConfig);

function authCallback(error, response) {
    // Handle redirect response
}

// Register a redirect callback for Success or Error (when using redirect methods)
// **REQUIRED** in MSAL.js 1.2.x and earlier
// **OPTIONAL** in MSAL.js 1.3.x and later
msalInstance.handleRedirectCallback(authCallback);

单实例和配置Single instance and configuration

MSAL.js 1.x 和 2.x 在设计上分别采用 UserAgentApplicationPublicClientApplication 的单个实例和配置,用于表示单个身份验证上下文。Both MSAL.js 1.x and 2.x are designed to have a single instance and configuration of the UserAgentApplication or PublicClientApplication, respectively, to represent a single authentication context.

不建议使用 UserAgentApplicationPublicClientApplication 的多个实例,因为它们会导致浏览器中出现有冲突的缓存条目和行为。Multiple instances of UserAgentApplication or PublicClientApplication are not recommended as they cause conflicting cache entries and behavior in the browser.

后续步骤Next steps

GitHub 上的此 MSAL.js 2.x 代码示例演示如何使用配置对象实例化 PublicClientApplicationThis MSAL.js 2.x code sample on GitHub demonstrates instantiation of a PublicClientApplication with a Configuration object:

Azure-Samples/ms-identity-javascript-v2Azure-Samples/ms-identity-javascript-v2