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

本快速入門使用範例 Angular 單頁應用程式 (SPA) 來示範如何使用授權碼流程搭配程式代碼交換證明密鑰來登入使用者,並呼叫 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:4200
  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/angular-spa

  2. 開啟 src/app/app.module.ts ,並使用先前在系統管理中心記錄的資訊來更新下列值。

    // Required for Angular multi-browser support
    import { BrowserModule } from '@angular/platform-browser';
    
    // Required for Angular
    import { NgModule } from '@angular/core';
    
    // Required modules and components for this application
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { ProfileComponent } from './profile/profile.component';
    import { HomeComponent } from './home/home.component';
    
    // HTTP modules required by MSAL
    import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
    
    // Required for MSAL
    import { IPublicClientApplication, PublicClientApplication, InteractionType, BrowserCacheLocation, LogLevel } from '@azure/msal-browser';
    import { MsalGuard, MsalInterceptor, MsalBroadcastService, MsalInterceptorConfiguration, MsalModule, MsalService, MSAL_GUARD_CONFIG, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG, MsalGuardConfiguration, MsalRedirectComponent } from '@azure/msal-angular';
    
    const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1;
    
    export function MSALInstanceFactory(): IPublicClientApplication {
      return new PublicClientApplication({
        auth: {
          // 'Application (client) ID' of app registration in the Microsoft Entra admin center - this value is a GUID
          clientId: "Enter_the_Application_Id_Here",
          // Full directory URL, in the form of https://login.microsoftonline.com/<tenant>
          authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here",
          // Must be the same redirectUri as what was provided in your app registration.
          redirectUri: "http://localhost:4200",
        },
        cache: {
          cacheLocation: BrowserCacheLocation.LocalStorage,
          storeAuthStateInCookie: isIE
        }
      });
    }
    
    // MSAL Interceptor is required to request access tokens in order to access the protected resource (Graph)
    export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
      const protectedResourceMap = new Map<string, Array<string>>();
      protectedResourceMap.set('https://graph.microsoft.com/v1.0/me', ['user.read']);
    
      return {
        interactionType: InteractionType.Redirect,
        protectedResourceMap
      };
    }
    
    // MSAL Guard is required to protect routes and require authentication before accessing protected routes
    export function MSALGuardConfigFactory(): MsalGuardConfiguration {
      return { 
        interactionType: InteractionType.Redirect,
        authRequest: {
          scopes: ['user.read']
        }
      };
    }
    
    // Create an NgModule that contains the routes and MSAL configurations
    @NgModule({
      declarations: [
        AppComponent,
        HomeComponent,
        ProfileComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
        MsalModule
      ],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: MsalInterceptor,
          multi: true
        },
        {
          provide: MSAL_INSTANCE,
          useFactory: MSALInstanceFactory
        },
        {
          provide: MSAL_GUARD_CONFIG,
          useFactory: MSALGuardConfigFactory
        },
        {
          provide: MSAL_INTERCEPTOR_CONFIG,
          useFactory: MSALInterceptorConfigFactory
        },
        MsalService,
        MsalGuard,
        MsalBroadcastService
      ],
      bootstrap: [AppComponent, MsalRedirectComponent]
    })
    export class AppModule { }
    
    • clientId - 應用程式的識別碼,也稱為用戶端。 將引號中的文字取代為 稍早記錄的應用程式(用戶端)標識碼 值。
    • authority - 授權單位是一個 URL,指出 MSAL 可以要求令牌的來源目錄。 將Enter_the_Tenant_Info_Here取代稍早記錄的 [目錄] [租使用者] 識別符值。
    • redirectUri - 應用程式的重新 導向 URI 。 如有必要,請將引號中的文字取代為稍早記錄的重新導向 URI。

執行應用程式並登入

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

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

    npm install
    npm start
    
  2. https複製終端機中顯示的 URL,https://localhost:4200例如 ,並將它貼到瀏覽器網址列中。 我們建議使用私人或 incognito 瀏覽器會話。

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

  4. 應用程式會要求許可權,以維護您授與數據存取權的許可權,以及登入並讀取配置檔。 選取 [接受]。 下列螢幕快照隨即出現,指出您已登入應用程式,並已從 Microsoft Graph API 存取您的設定檔詳細數據。

    描述 API 呼叫結果的 JavaScript 應用程式螢幕快照。

從應用程式註銷

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

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