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

本快速入門使用範例 JavaScript (JS) 單頁應用程式 (SPA) 來示範如何使用授權碼流程搭配 Code Exchange 證明金鑰 (PKCE) 來登入使用者,並呼叫 Microsoft Graph API。 此範例會使用適用於 JavaScriptMicrosoft 驗證連結庫來處理驗證。

必要條件

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

若要完成註冊,請提供應用程式名稱、指定支援的帳戶類型,以及新增重新導向 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. 系統會提示您挑選要註銷的帳戶。 選取您用來登入的帳戶。

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