共用方式為


快速入門:使用 JavaScript 在單頁應用程式 (SPA) 中登入使用者,並呼叫 Microsoft Graph API

本快速入門使用範例 JavaScript (JS) 單頁應用程式 (SPA),向您示範如何使用授權碼流程 (部分機器翻譯) 搭配程式碼交換證明金鑰 (PKCE) 來登入使用者,並呼叫 Microsoft Graph API。 此範例使用適用於 JavaScript 的 Microsoft 驗證程式庫 (英文) 來處理驗證。

必要條件

註冊應用程式和記錄識別碼

若要完成註冊,請提供應用程式名稱、指定支援的帳戶類型,以及新增重新導向 URI。 註冊之後,應用程式 [概觀] 窗格會顯示應用程式原始程式碼中所需的識別碼。

  1. 登入 Microsoft Entra 系統管理中心。

  2. 如果您有多個租用戶的存取權,請使用頂端功能表中的 [設定] 圖示 ,從 [目錄 + 訂用帳戶] 功能表來切換至您要在其中註冊應用程式的租用戶。

  3. 瀏覽至 [身分識別] > [應用程式] > [應用程式註冊],選取 [新增註冊]

  4. 輸入應用程式的 [名稱],例如 identity-client-spa

  5. 在 [支援的帳戶類型] 區段中,選取 [僅限此組織目錄中的帳戶]。 如需不同帳戶類型的資訊,請選取 [協助我選擇] 選項。

  6. 選取註冊

    螢幕擷取畫面顯示如何在 Microsoft Entra 系統管理中心輸入名稱並選取帳戶類型。

  7. 註冊完成時,即會顯示應用程式的 [概觀] 窗格。 記錄 [目錄 (租用戶) 識別碼] 和 [應用程式 (用戶端) 識別碼],以用於您的應用程式原始程式碼。

    螢幕擷取畫面顯示 Microsoft Entra 系統管理中心概觀頁面上的識別碼值。

    注意

    您可以參考修改應用程式所支援的帳戶,以變更 [支援的帳戶類型]

新增平台重新導向 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.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: [],
    };
    
    /**
     * 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 - 應用程式 (也稱為用戶端) 的識別碼。 將引號中的文字取代為先前記錄的 [應用程式 (用戶端) 識別碼] 值。
    • authority - 授權單位是一個 URL,指出 MSAL 可以向其要求權杖的目錄。 將 Enter_the_Tenant_Info_Here 取代為先前記錄的 [目錄 (租用戶) 識別碼] 值。
    • redirectUri - 應用程式的 [重新導向 URI]。 如有必要,請將引號中的文字取代為先前記錄的重新導向 URI。

執行應用程式並登入

使用 Node.js 以網頁伺服器執行專案:

  1. 若要啟動伺服器,請從專案目錄執行下列命令:

    npm install
    npm start
    
  2. 複製終端機中顯示的 https URL,例如 https://localhost:3000,並將其貼到瀏覽器中。 建議您使用私人或 Incognito 瀏覽器工作階段。

  3. 請遵循步驟並輸入必要的詳細資料,以使用您的 Microsoft 帳戶登入。 系統會向您要求電子郵件地址,以便將一次性密碼傳送給您。 出現提示時,請輸入程式碼。

  4. 應用程式會要求權限,從而對您已授與其存取權的資料保有存取權限,以及讓您登入並讀取設定檔。 選取 [接受]。 下列螢幕擷取畫面隨即出現,指出您已登入應用程式,並已從 Microsoft Graph API 存取您的設定檔詳細資料。

    描述 API 呼叫結果的 JavaScript 應用程式螢幕擷取畫面。

從應用程式登出

  1. 尋找頁面右上角的 [登出] 按鈕,然後加以選取。
  2. 系統會提示您挑選要登出的帳戶。 選取您用來登入的帳戶。

隨即出現訊息,指出您已登出。您現在可以關閉瀏覽器視窗。