MSAL Angular のイベント

ここで開始する前に、 アプリケーション オブジェクトを初期化する方法を理解していることを確認してください。

@azure/msal-angular は、認証と MSAL に関連するイベントを出力する @azure/msal-browserによって公開されるイベント システムを使用します。また、UI の更新やエラー メッセージの表示などにも使用できます。

アプリでのイベントの消費

@azure/msal-angularのイベントは、MsalBroadcastServiceによって管理され、msalSubject$で監視可能なMsalBroadcastServiceをサブスクライブすることによって使用できます。

アプリケーションで生成されたイベントを使用する方法の例を次に示します。

import { MsalBroadcastService } from '@azure/msal-angular';
import { EventMessage, EventType } from '@azure/msal-browser';

export class AppComponent implements OnInit, OnDestroy {
  private readonly _destroying$ = new Subject<void>();

  constructor(
    //...
    private msalBroadcastService: MsalBroadcastService
  ) {}

  ngOnInit(): void {
    this.msalBroadcastService.msalSubject$
      .pipe(
        // Optional filtering of events.
        filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS), 
        takeUntil(this._destroying$)
      )
      .subscribe((result: EventMessage) => {
        // Do something with the result
      });
  }

  ngOnDestroy(): void {
    this._destroying$.next(null);
    this._destroying$.complete();
  }
}

コンパイル エラーを防ぐために、 result.payload を特定の型としてキャストする必要がある場合があることに注意してください。 ペイロードの種類はイベントによって異なります。 こちらのドキュメントで確認できます。

ngOnInit(): void {
  this.msalBroadcastService.msalSubject$
    .pipe(
      filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),
    )
    .subscribe((result: EventMessage) => {
      // Casting payload as AuthenticationResult to access account
      const payload = result.payload as AuthenticationResult;
      this.authService.instance.setActiveAccount(payload.account);
    });
}

イベントを使用する完全な例については、 こちらのサンプルを参照してください。

イベントの表

EventMessageによって現在出力されているイベントの完全なテーブル (説明や関連するペイロードを含む) など、@azure/msal-browser オブジェクトの詳細については、こちらのドキュメントを参照してください。

イベントでのエラーの処理

EventErrorEventMessageAuthError | Error | nullとして定義されているため、エラーは、その上の特定のプロパティにアクセスする前に、正しい型として検証する必要があります。

TypeScript エラーを回避するためにエラーを AuthError にキャストする方法の次の例を参照してください。

import { MsalBroadcastService } from '@azure/msal-angular';
import { EventMessage, EventType } from '@azure/msal-browser';

export class AppComponent implements OnInit, OnDestroy {
  private readonly _destroying$ = new Subject<void>();

  constructor(
    //...
    private msalBroadcastService: MsalBroadcastService
  ) {}

  ngOnInit(): void {
    this.msalBroadcastService.msalSubject$
      .pipe(
        // Optional filtering of events
        filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_FAILURE), 
        takeUntil(this._destroying$)
      )
      .subscribe((result: EventMessage) => {
        if (result.error instanceof AuthError) {
          // Do something with the error
        }
      });
  }

  ngOnDestroy(): void {
    this._destroying$.next(null);
    this._destroying$.complete();
  }
}

エラー処理の例は、 MSAL Angular B2C サンプルでも確認できます。

タブとウィンドウ間でログに記録された状態を同期する

ユーザーが別のタブまたはウィンドウでアプリにログインまたはログアウトするときに UI を更新する場合は、 ACCOUNT_ADDEDACCOUNT_REMOVED イベントをサブスクライブできます。 ペイロードは、追加または削除された AccountInfo オブジェクトになります。

import { MsalService, MsalBroadcastService } from '@azure/msal-angular';
import { EventMessage, EventType } from '@azure/msal-browser';

export class AppComponent implements OnInit, OnDestroy {
  private readonly _destroying$ = new Subject<void>();

  constructor(
    //...
    private authService: MsalService,
    private msalBroadcastService: MsalBroadcastService
  ) {}

  ngOnInit(): void {
    this.authService.instance.enableAccountStorageEvents(); // Register the storage listener that will be emitting the events
    this.msalBroadcastService.msalSubject$
      .pipe(
        // Optional filtering of events
        filter((msg: EventMessage) => msg.eventType === EventType.ACCOUNT_ADDED || msg.eventType === EventType.ACCOUNT_REMOVED), 
        takeUntil(this._destroying$)
      )
      .subscribe((result: EventMessage) => {
        if (this.authService.msalInstance.getAllAccounts().length === 0) {
          // Account logged out in a different tab, redirect to homepage
          window.location.pathname = "/";
        } else {
          // Update UI to show user is signed in. result.payload contains the account that was logged in
        }
      });
  }

  ngOnDestroy(): void {
    this._destroying$.next(null);
    this._destroying$.complete();
  }
}

完全な例は、 サンプルでも確認できます。

inProgress$ Observable

監視可能な inProgress$MsalBroadcastServiceによっても処理され、特に相互作用が完了したことを確認するために、アプリケーションが対話の状態を知る必要があるときにサブスクライブする必要があります。 ユーザー アカウントを含む関数の前に、対話の状態が InteractionStatus.None されていることを確認することをお勧めします。

最後の、つまり最新の InteractionStatus も、inProgress$ Observable をサブスクライブした際に利用できることに注意してください。

その使用については、次の例を参照してください。 完全な例は、 サンプルでも確認できます。 対話状態の完全な一覧 については、こちらをご覧ください

import { Component, OnInit, Inject, OnDestroy } from '@angular/core';
import { MsalBroadcastService} from '@azure/msal-angular';
import { InteractionStatus } from '@azure/msal-browser';
import { Subject } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  private readonly _destroying$ = new Subject<void>();

  constructor(
    private msalBroadcastService: MsalBroadcastService
  ) {}

  ngOnInit(): void {
    this.msalBroadcastService.inProgress$
      .pipe(
        // Filtering for all interactions to be completed
        filter((status: InteractionStatus) => status === InteractionStatus.None),
        takeUntil(this._destroying$)
      )
      .subscribe(() => {
        // Do something related to user accounts or UI here
      })
  }

  ngOnDestroy(): void {
    this._destroying$.next(null);
    this._destroying$.complete();
  }
}

オプションの MsalBroadcastService 構成

MsalBroadcastServiceは、必要に応じて、サブスクライブ時に過去のイベントを再生するように構成できます。 既定では、 MsalBroadcastService のサブスクライブ後に生成されるイベントを使用できます。 サブスクリプションより前のイベントが必要な場合があります。 MsalBroadcastServiceの構成を指定し、eventsToReplay パラメーターを数値に設定することで、サブスクリプションでその数の過去のイベントを使用できるようになります。

イベントの再生の詳細については、ReplaySubjects の RxJS ドキュメント を参照してください

MsalBroadcastServiceは、app.module.ts ファイルで次のように構成できます。

// app.module.ts
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { MsalModule, MsalService, MsalGuard, MsalInterceptor, MsalBroadcastService, MsalRedirectComponent, MSAL_BROADCAST_CONFIG } from "@azure/msal-angular"; // Import MsalBroadcastService and MSAL_BROADCAST_CONFIG here
import { PublicClientApplication, InteractionType, BrowserCacheLocation } from "@azure/msal-browser";

@NgModule({
    imports: [
        MsalModule.forRoot( new PublicClientApplication({ // MSAL Configuration
            auth: {
                clientId: "clientid",
                authority: "https://login.microsoftonline.com/common/",
                redirectUri: "http://localhost:4200/",
                postLogoutRedirectUri: "http://localhost:4200/",
                navigateToLoginRequestUrl: true
            },
            cache: {
                cacheLocation : BrowserCacheLocation.LocalStorage,
            },
            system: {
                loggerOptions: {
                    loggerCallback: () => {},
                    piiLoggingEnabled: false
                }
            }
        }), {
            interactionType: InteractionType.Popup, // MSAL Guard Configuration
            authRequest: {
              scopes: ['user.read']
            },
            loginFailedRoute: "/login-failed" 
        }, {
            interactionType: InteractionType.Redirect, // MSAL Interceptor Configuration
            protectedResourceMap
        })
    ],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: MsalInterceptor,
            multi: true
        },
        {
          provide: MSAL_BROADCAST_CONFIG, // Add configuration to providers here
          useValue: {
            eventsToReplay: 2 // Set how many events you want to replay when subscribing
          }
        },
        MsalGuard,
        MsalBroadcastService // Ensure the MsalBroadcastService is provided
    ],
    bootstrap: [AppComponent, MsalRedirectComponent]
})
export class AppModule {}