快速入門:登入使用者,並在 JavaScript SPA 中取得存取令牌

在本快速入門中,您會下載並執行程式碼範例,示範 JavaScript 單頁應用程式 (SPA) 如何登入使用者並呼叫 Microsoft Graph。 程式代碼範例也會示範如何取得存取令牌來呼叫 Microsoft Graph API 或任何 Web API。

請參閱 範例 的運作方式以取得圖例。

必要條件

提示

本文中的步驟可能會根據您從開始的入口網站稍有不同。

註冊並下載快速入門應用程式

若要啟動快速入門應用程式,請使用下列其中一個選項。

選項 1 (Express):註冊並自動設定您的應用程式,然後下載您的程式碼範例

  1. 登入 Azure 入口網站 - 應用程式註冊 快速入門體驗。
  2. 輸入應用程式的名稱。
  3. 在 [支持的帳戶類型] 下,選取 [任何組織目錄和個人 Microsoft 帳戶中的帳戶]。
  4. 選取註冊
  5. 請依照指示下載並自動設定新的應用程式。

選項 2 (手動):註冊並手動設定您的應用程式和程式代碼範例

步驟 1:註冊您的應用程式

  1. 登入 Azure 入口網站
  2. 如果您有多個租使用者的存取權,請使用頂端功能表中的 [設定] 圖示,選取您要在其中註冊應用程式的租使用者。
  3. 搜尋並選取 [ 身分識別]。
  4. 在 [管理] 底下,選取 [應用程式註冊]> [新增註冊]
  5. 輸入應用程式的 [ 名稱 ]。 您的應用程式使用者可能會看到此名稱,而且您稍後可以加以變更。
  6. 在 [支持的帳戶類型] 下,選取 [任何組織目錄和個人 Microsoft 帳戶中的帳戶]。
  7. 選取註冊。 在應用程式 [概 觀] 頁面上,記下 應用程式 (用戶端) 識別碼 值以供稍後使用。
  8. 本快速入門需要 啟用隱含授與流程 。 在 [管理] 底下,選取 [驗證]
  9. 在 [平台組態>] 底下新增平臺。 選取 Web
  10. 將 [ 重新導向 URI ] 值設定為 http://localhost:3000/
  11. 選取 [隱含授與和混合式流程] 底下的 [存取令牌和標識符令牌]。
  12. 選取設定

步驟 1:在 Azure 入口網站 中設定您的應用程式

若要讓本快速入門中的程式碼範例能夠運作,請新增http://localhost:3000/重新導向 URI 並啟用隱含授

Already configured 您的應用程式會使用這些屬性進行設定。

步驟 2:下載專案

若要使用 Node.js 以網頁伺服器執行專案, 請下載核心項目檔

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

步驟 3:設定 JavaScript 應用程式

JavaScriptSPA 資料夾中,編輯authConfig.js,並在下msalConfig設定clientIDauthorityredirectUri 值。


 // Config object to be passed to Msal on creation
 const msalConfig = {
   auth: {
     clientId: "Enter_the_Application_Id_Here",
     authority: "Enter_the_Cloud_Instance_Id_Here/Enter_the_Tenant_Info_Here",
     redirectUri: "Enter_the_Redirect_Uri_Here",
   },
   cache: {
     cacheLocation: "sessionStorage", // This configures where your cache will be stored
     storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
   }
 };

注意

Enter_the_Supported_Account_Info_Here

其中:

  • Enter_the_Application_Id_Here是您註冊之應用程式的應用程式 (用戶端) 識別碼

    若要尋找應用程式 (用戶端) 識別碼的值,請移至應用程式 Azure 入口網站 中的 [概觀] 頁面。

  • Enter_the_Cloud_Instance_Id_Here 是 Azure 雲端的實例。 針對主要或全域 Azure 雲端,只要輸入 https://login.microsoftonline.com/即可。 如需 國家 雲端(例如中國),請參閱 國家雲端

  • Enter_the_Tenant_info_here 設定為下列其中一個選項:

    • 如果您的應用程式支援此組織目錄中的帳戶,請將此值取代為租使用者識別碼租使用者名稱(例如, 。 contoso.microsoft.com

    若要尋找目錄 (租使用者) 識別碼的值,請移至 Azure 入口網站 中的應用程式註冊 [概觀] 頁面。

    • 如果您的應用程式支援 任何組織目錄中的帳戶,請將此值取代為 organizations
    • 如果您的應用程式支援 任何組織目錄和個人 Microsoft 帳戶中的帳戶,請將此值取代為 common。 若要限制僅對個人 Microsoft 帳戶的支援,請將此值取代為 consumers

    若要尋找支持的帳戶類型,請移至應用程式註冊的 [概觀] 頁面,Azure 入口網站。

  • Enter_the_Redirect_Uri_Herehttp://localhost:3000/

步驟 3:您的應用程式已設定並準備好執行

我們已使用您 app 屬性的值來設定您的專案。

然後,仍然位於相同的資料夾中,編輯 graphConfig.js 檔案來設定 graphMeEndpointgraphMeEndpointapiConfig 物件。

  // Add here the endpoints for MS Graph API services you would like to use.
  const graphConfig = {
    graphMeEndpoint: "Enter_the_Graph_Endpoint_Here/v1.0/me",
    graphMailEndpoint: "Enter_the_Graph_Endpoint_Here/v1.0/me/messages"
  };

  // Add here scopes for access token to be used at MS Graph API endpoints.
  const tokenRequest = {
      scopes: ["Mail.Read"]
  };

其中:

  • <> Enter_the_Graph_Endpoint_Here是 API 呼叫所針對的端點。 針對主要或全域 Microsoft Graph API 服務,只要輸入 https://graph.microsoft.com/即可。 如需詳細資訊,請參閱 國家雲端部署

步驟 4:執行專案

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

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

    npm install
    npm start
    
  2. 開啟網頁瀏覽器並移至 http://localhost:3000/

  3. 選取 [登入 ] 以啟動登入,然後呼叫 Microsoft Graph API。

在瀏覽器載入應用程式之後,選取 [ 登入]。 第一次登入時,系統會提示您提供同意,以允許應用程式存取您的配置檔並登入。 成功登入之後,您的使用者配置檔資訊應該會顯示在頁面上。

其他相關資訊

範例的運作方式

How the sample JavaScript SPA works: 1. The SPA initiates sign in. 2. The SPA acquires an ID token from the Microsoft identity platform. 3. The SPA calls acquire token. 4. The Microsoft identity platform returns an Access token to the SPA. 5. The SPA makes and HTTP GET request with the Access Token to the Microsoft Graph API. 6. The Graph API returns an HTTP response to the SPA.

msal.js

MSAL 連結庫會登入使用者,並要求用來存取受 Microsoft 身分識別平台 保護的 API 的令牌。 快速入門 index.html 檔案包含連結庫的參考:

<script type="text/javascript" src="https://alcdn.msftauth.net/lib/1.2.1/js/msal.js" integrity="sha384-9TV1245fz+BaI+VvCjMYL0YDMElLBwNS84v3mY57pXNOt6xcUYch2QLImaTahcOP" crossorigin="anonymous"></script>

您可以在 MSAL.js 版底下,將上述版本取代為最新版本。

或者,如果您已安裝Node.js,您可以透過 Node.js 封裝管理員 (npm) 下載最新版本:

npm install msal

MSAL 初始化

快速入門程式代碼也會示範如何初始化 MSAL 連結庫:

  // Config object to be passed to Msal on creation
  const msalConfig = {
    auth: {
      clientId: "75d84e7a-40bx-f0a2-91b9-0c82d4c556aa", // this is a fake id
      authority: "https://login.microsoftonline.com/common",
      redirectUri: "http://localhost:3000/",
    },
    cache: {
      cacheLocation: "sessionStorage", // This configures where your cache will be stored
      storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
    }
  };

const myMSALObj = new Msal.UserAgentApplication(msalConfig);
其中 描述
clientId Azure 入口網站 中註冊之應用程式的應用程式標識碼。
authority (選擇性)支持帳戶類型的授權單位 URL,如先前的組態一節所述。 預設授權單位為 https://login.microsoftonline.com/common
redirectUri 應用程式註冊的已設定回復/redirectUri。 在此情況下,http://localhost:3000/
cacheLocation (選擇性)設定驗證狀態的瀏覽器記憶體。 預設值為 session 儲存體。
storeAuthStateInCookie (選擇性)儲存驗證要求狀態的連結庫,用於驗證瀏覽器 Cookie 中的驗證流程。 此 Cookie 是針對 IE 和 Edge 瀏覽器所設定,可減輕某些 已知問題

如需可用可設定選項的詳細資訊,請參閱 初始化用戶端應用程式

登入使用者

下列代碼段示範如何登入使用者:

// Add scopes for the id token to be used at Microsoft identity platform endpoints.
const loginRequest = {
    scopes: ["openid", "profile", "User.Read"],
};

myMSALObj.loginPopup(loginRequest)
    .then((loginResponse) => {
    //Login Success callback code here
}).catch(function (error) {
    console.log(error);
});
其中 描述
scopes (選擇性)包含登入時要求使用者同意的範圍。 例如, [ "user.read" ] 針對 Microsoft Graph 或 [ "<Application ID URL>/scope" ] 自訂 Web API(也就是 api://<Application ID>/access_as_user)。

或者,您可能想要使用 loginRedirect 方法,將目前的頁面重新導向至登入頁面,而不是彈出視窗。

要求令牌

MSAL 使用三種方法來取得令牌: acquireTokenRedirectacquireTokenPopupacquireTokenSilent

以無訊息方式取得使用者令牌

acquireTokenSilent方法會處理令牌擷取和更新,而不需要任何用戶互動。 loginRedirect第一次執行 或 loginPopup 方法之後,是常用來取得令牌的方法,acquireTokenSilent用來存取受保護資源的後續呼叫。 要求或更新令牌的呼叫會以無訊息方式進行。


const tokenRequest = {
    scopes: ["Mail.Read"]
};

myMSALObj.acquireTokenSilent(tokenRequest)
    .then((tokenResponse) => {
        // Callback code here
        console.log(tokenResponse.accessToken);
    }).catch((error) => {
        console.log(error);
    });
其中 描述
scopes 包含要求在 API 存取令牌中傳回的範圍。 例如, [ "mail.read" ] 針對 Microsoft Graph 或 [ "<Application ID URL>/scope" ] 自訂 Web API(也就是 api://<Application ID>/access_as_user)。

以互動方式取得使用者令牌

在某些情況下,您會強制使用者與 Microsoft 身分識別平台 互動。 例如:

  • 使用者可能需要重新輸入其認證,因為其密碼已過期。
  • 您的應用程式要求存取使用者需要同意的其他資源範圍。
  • 需要雙因素驗證。

大部分應用程式通常建議的模式是先呼叫 acquireTokenSilent ,然後攔截例外狀況,然後呼叫 acquireTokenPopup (或 acquireTokenRedirect) 以啟動互動式要求。

acquireTokenPopup在彈出視窗中呼叫結果以登入。 (或acquireTokenRedirect會導致將使用者重新導向至 Microsoft 身分識別平台)。 在該視窗中,用戶必須藉由確認其認證、同意所需的資源,或完成雙因素驗證來進行互動。

// Add here scopes for access token to be used at MS Graph API endpoints.
const tokenRequest = {
    scopes: ["Mail.Read"]
};

myMSALObj.acquireTokenPopup(requestObj)
    .then((tokenResponse) => {
        // Callback code here
        console.log(tokenResponse.accessToken);
    }).catch((error) => {
        console.log(error);
    });

注意

本快速入門使用 loginRedirect 和 方法搭配 Microsoft Internet Explorer,因為 Internet Explorer 處理彈出視窗的已知問題acquireTokenRedirect

下一步

如需為本快速入門建置應用程式的詳細逐步指南,請參閱: