クイックスタート: シングルページ アプリ (SPA) でユーザーをサインインし、Angular を使用して Microsoft Graph API を呼び出す

このクイックスタートでは、サンプルの Angular シングルページ アプリ (SPA) を使用して、Proof Key for Code Exchange (PKCE) で承認コード フローを使用してユーザーをサインインさせ、Microsoft Graph API を呼び出す方法を紹介します。 このサンプルでは、JavaScript 用 Microsoft Authentication Library を使用して認証を処理します。

前提条件

アプリケーションとレコードの識別子を登録する

登録を完了するには、アプリケーションに名前を指定し、サポートされているアカウントの種類を指定して、リダイレクト URI を追加します。 登録すると、アプリケーションの [概要] ペインに、アプリケーションのソース コードに必要な識別子が表示されます。

  1. Microsoft Entra 管理センターにサインインします。

  2. 複数のテナントにアクセスできる場合は、上部のメニューの [設定] アイコン を使い、[ディレクトリとサブスクリプション] メニューからアプリケーションを登録するテナントに切り替えます。

  3. [ID]>[アプリケーション]>[アプリ登録] の順に進み、[新規登録] を選択します。

  4. アプリケーションの名前 (identity-client-spa など) を入力します。

  5. [サポートされているアカウントの種類] で、 [この組織のディレクトリ内のアカウントのみ] を選択します。 さまざまなアカウントの種類の詳細については、[選択に関するヘルプ] オプションを選択します。

  6. [登録] を選択します。

    Microsoft Entra 管理センターで名前を入力し、アカウントの種類を選ぶ方法を示すスクリーンショット。

  7. 登録が完了すると、アプリケーションの [概要] ペインが表示されます。 アプリケーションのソース コードで使用するディレクトリ (テナント) IDアプリケーション (クライアント) ID を記録します。

    Microsoft Entra 管理センターの概要ページに表示される識別子の値を示すスクリーンショット。

    Note

    サポートされているアカウントの種類は、「アプリケーションによってサポートされるアカウントを変更する」を参照して変更することができます。

プラットフォーム リダイレクト 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 - クライアントとも呼ばれる、アプリケーションの識別子。 引用符で囲まれた文字を先ほど記録した アプリケーション (クライアント) ID の値に置き換えます。
    • authority - 機関は、MSAL がトークンを要求できるディレクトリを示す URL です。 Enter_the_Tenant_Info_Here を、先ほど記録したディレクトリ (テナント) ID の値に置き換えます。
    • redirectUri - アプリケーションのリダイレクト URI。 必要に応じて引用符で囲まれた文字をから先ほど記録したリダイレクト URI の値に置き換えてください。

アプリケーションを実行し、サインインします

Node.js を使用して Web サーバーでプロジェクトを実行します。

  1. サーバーを起動するために、プロジェクト ディレクトリ内から次のコマンドを実行します。

    npm install
    npm start
    
  2. ターミナルに表示される https の URL (例: https://localhost:4200) をコピーし、ブラウザーのアドレス バーに貼り付けます。 ブラウザーのプライベート セッションまたはシークレット セッションを使用することを推奨します。

  3. 手順に従って必要な詳細情報を入力し、Microsoft アカウントでサインインしてください。 ワンタイム パスコードを送信できるように、メール アドレスが要求されます。 プロンプトが表示されたら、パスコードを入力します。

  4. アプリケーションは、アクセス権を付与したデータへのアクセスを維持し、サインインしてプロファイルを読み取るアクセス許可を要求します。 [Accept](承認) を選択します。 次のスクリーンショットは、アプリケーションにサインインし、Microsoft Graph API からプロファイルの詳細にアクセスしたことを示しています。

    API 呼び出しの結果を示す JavaScript アプリのスクリーンショット。

アプリケーションからサインアウトする

  1. ページの右上隅にある [サインアウト] ボタンを見つけて選択してください。
  2. サインアウト元のアカウントを選択するように求められます。 サインインに使用したアカウントを選択します。

サインアウトしたことを示すメッセージが表示されます。ブラウザー ウィンドウを閉じます。