Share via


使用 MSAL.js初始化用戶端應用程式

本文說明使用使用者代理程式應用程式的實例初始化適用於 JavaScript 的 Microsoft 驗證連結庫(MSAL.js)。

使用者代理程式應用程式是公用用戶端應用程式的形式,其中用戶端程式代碼會在使用者代理程式中執行,例如網頁瀏覽器。 這類用戶端不會儲存秘密,因為瀏覽器內容是可公開存取的。

若要深入瞭解用戶端應用程式類型和應用程式組態選項,請參閱 MSAL 中的公用和機密用戶端應用程式。

必要條件

在初始化應用程式之前,您必須先在 Microsoft Entra 系統管理中心註冊該應用程式,以建立應用程式與 Microsoft 身分識別平台 之間的信任關係。

註冊您的應用程式之後,您將需要一些或所有可在 Microsoft Entra 系統管理中心找到的值。

必要 描述
應用程式 (用戶端) 識別碼 必要 可唯一識別應用程式在 Microsoft 身分識別平台 內的 GUID。
授權單位 選擇性 應用程式的識別提供者 URL(實例)和登入物件。 串連時,實例和登入物件會組成 授權單位
目錄 (租用戶) 識別碼 選擇性 如果您要只為您的組織建置企業營運應用程式,請指定目錄(租用戶)標識碼,通常稱為單一 租用戶應用程式
重新導向 URI 選擇性 如果您要建置 Web 應用程式,則會redirectUri指定識別提供者 (Microsoft 身分識別平台) 應傳回它所簽發的安全性令牌的位置。

初始化 MSAL.js 2.x 應用程式

使用 Configuration 物件具現化 PublicClientApplication,初始化MSAL.js驗證內容。 所需的最低組態屬性是clientID應用程式的 ,在 Microsoft Entra 系統管理中心的應用程式註冊 [概觀] 頁面上顯示為 [應用程式] [用戶端] 識別碼

以下是 群組態物件的範例和 具 PublicClientApplication現化 :

const msalConfig = {
  auth: {
    clientId: "Enter_the_Application_Id_Here",
    authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here",
    knownAuthorities: [],
    redirectUri: "https://localhost:{port}/redirect",
    postLogoutRedirectUri: "https://localhost:{port}/redirect",
    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

當應用程式使用重新導向流程時,叫 用 handleRedirectPromise 。 使用重新導向流程時, handleRedirectPromise 應該在每個頁面載入上執行。

從承諾中可以取得三個結果:

  • .then 會叫用且 tokenResponse 真實:應用程式會從成功的重新導向作業傳回。
  • .then 會叫用 ,而且 tokenResponse 是假的(null):應用程式不會從重新導向作業傳回。
  • .catch 已叫用:應用程式從重新導向作業傳回,而且發生錯誤。

初始化 MSAL.js 1.x 應用程式

使用組態物件具現化 UserAgentApplication,初始化 MSAL 1.x 驗證內容。 您應用程式的最低必要組態屬性是clientID應用程式的 ,在 Microsoft Entra 系統管理中心的應用程式註冊 [概觀] 頁面上顯示為應用程式(用戶端)標識碼

針對具有重新導向流程的驗證方法(loginRedirect 和 acquireTokenRedirect),MSAL.js 1.2.x 或更早版本中,您必須透過 方法明確註冊回呼以取得成功或錯誤 handleRedirectCallback() 。 MSAL.js 1.2.x 和更早版本中需要明確註冊回呼,因為重新導向流程不會傳回像具有快顯體驗的方法一樣的承諾。 MSAL.js 1.3.x 版和更新版本中註冊回呼是 選擇性 的。

// Configuration object constructed
const msalConfig = {
  auth: {
    clientId: "Enter_the_Application_Id_Here",
  },
};

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

單一實例和組態

MSAL.js 1.x 和 2.x 都設計成分別具有 或 PublicClientApplication的單一實例和組態UserAgentApplication,以代表單一驗證內容。

不建議使用 或 PublicClientApplicationUserAgentApplication多個實例,因為它們可能會導致瀏覽器中的快取專案和行為衝突。

下一步

GitHub 上的 MSAL.js 2.x 程式代碼範例示範使用 Configuration 物件具現化 PublicClientApplication