次の方法で共有


Azure Active Directory B2C を使用して独自の Angular アプリケーションで認証を有効にするEnable authentication in your own Angular Application by using Azure Active Directory B2C

重要

2025 年 5 月 1 日より、Azure AD B2C は新規のお客様向けに購入できなくなります。 詳細については、FAQ を参照してください

この記事では、Azure Active Directory B2C (Azure AD B2C) 認証を独自の Angular シングルページ アプリケーション (SPA) に追加する方法について説明します。 Angular アプリケーションを MSAL for Angular 認証ライブラリと統合する方法について説明します。

この記事を、 サンプルの Angular シングルページ アプリケーションでの認証の構成というタイトルの関連記事と共に使用してください。 サンプルの Angular アプリを独自の Angular アプリに置き換えます。 この記事の手順を完了すると、アプリケーションは Azure AD B2C 経由のサインインを受け入れるようになります。

[前提条件]

サンプルの Angular シングルページ アプリケーションでの認証の構成に関する記事の手順を完了します。

Angular アプリ プロジェクトを作成する

既存の Angular アプリ プロジェクトを使用することも、新しいプロジェクトを作成することもできます。 新しいプロジェクトを作成するには、次のコマンドを実行します。

コマンドは次のとおりです。

  1. npm パッケージ マネージャーを使用して Angular CLI をインストールします。
  2. ルーティングモジュールを使用してAngularワークスペースを作成します。 アプリ名は msal-angular-tutorial です。 これは、 contoso-car-service などの任意の有効な Angular アプリ名に変更できます。
  3. アプリのディレクトリフォルダに移動します。
npm install -g @angular/cli 
ng new msal-angular-tutorial --routing=true --style=css --strict=false
cd msal-angular-tutorial

依存関係をインストールする

アプリケーションに MSAL Browser ライブラリと MSAL Angular ライブラリをインストールするには、コマンド シェルで次のコマンドを実行します。

npm install @azure/msal-browser @azure/msal-angular

Angular Material コンポーネントライブラリをインストールします (UI の場合はオプション)。

npm install @angular/material @angular/cdk

認証コンポーネントを追加する

サンプル コードは、次のコンポーネントで構成されています。

コンポーネント タイプ 説明
auth-config.ts 定数 この構成ファイルには、Azure AD B2C ID プロバイダーと Web API サービスに関する情報が含まれています。 Angular アプリは、この情報を使用して、Azure AD B2C との信頼関係の確立、ユーザーのサインインとサインアウト、トークンの取得、トークンの検証を行います。
app.module.ts Angularモジュール このコンポーネントは、アプリケーション パーツがどのように組み合わされるかを示します。 これは、アプリケーションをブートストラップして開くために使用されるルートモジュールです。 このチュートリアルでは、 app.module.ts モジュールにいくつかのコンポーネントを追加し、MSAL 構成オブジェクトを使用して MSAL ライブラリを起動します。
app-routing.module.ts Angular ルーティングモジュール このコンポーネントは、ブラウザのURLを解釈し、対応するコンポーネントをロードすることでナビゲーションを可能にします。 このチュートリアルでは、ルーティング モジュールにいくつかのコンポーネントを追加し、 MSAL Guard を使用してコンポーネントを保護します。 許可されたユーザーのみが保護されたコンポーネントにアクセスできます。
app.component.* 角度コンポーネント ng newコマンドは、ルートコンポーネントを持つAngularプロジェクトを作成しました。 このチュートリアルでは、トップ ナビゲーション バーをホストするように アプリ コンポーネントを変更します。 ナビゲーションバーには、サインインボタンやサインアウトボタンなど、さまざまなボタンがあります。 app.component.ts クラスは、サインイン イベントとサインアウト イベントを処理します。
home.component.* 角度コンポーネント このチュートリアルでは、匿名アクセス用のホーム ページをレンダリングするための home コンポーネントを追加します。 このコンポーネントは、ユーザーがサインインしたかどうかを確認する方法を示しています。
profile.component.* 角度コンポーネント このチュートリアルでは、 プロファイル コンポーネントを追加して、ID トークン要求の読み取り方法を学習します。
webapi.component.* 角度コンポーネント このチュートリアルでは、 webapi コンポーネントを追加して、Web API を呼び出す方法を学習します。

次のコンポーネントをアプリに追加するには、次の Angular CLI コマンドを実行します。 generate componentコマンドは、次のとおりです。

  1. 各コンポーネントのフォルダを作成します。 このフォルダには、TypeScript、HTML、CSS、およびテストファイルが含まれています。
  2. app.module.ts ファイルと app-routing.module.ts ファイルを新しいコンポーネントへの参照で更新します。
ng generate component home
ng generate component profile
ng generate component webapi

アプリの設定を追加する

Azure AD B2C ID プロバイダーと Web API の設定は、 auth-config.ts ファイルに格納されます。 src/app フォルダに、次のコードを含む auth-config.ts という名前のファイルを作成します。 次に、「 3.1 Angular サンプルを構成する」の説明に従って設定を変更します。

import { LogLevel, Configuration, BrowserCacheLocation } from '@azure/msal-browser';

const isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 || window.navigator.userAgent.indexOf("Trident/") > -1;
 
export const b2cPolicies = {
     names: {
         signUpSignIn: "b2c_1_susi_reset_v2",
         editProfile: "b2c_1_edit_profile_v2"
     },
     authorities: {
         signUpSignIn: {
             authority: "https://your-tenant-name.b2clogin.com/your-tenant-name.onmicrosoft.com/b2c_1_susi_reset_v2",
         },
         editProfile: {
             authority: "https://your-tenant-name.b2clogin.com/your-tenant-name.onmicrosoft.com/b2c_1_edit_profile_v2"
         }
     },
     authorityDomain: "your-tenant-name.b2clogin.com"
 };
 
 
export const msalConfig: Configuration = {
     auth: {
         clientId: '<your-MyApp-application-ID>',
         authority: b2cPolicies.authorities.signUpSignIn.authority,
         knownAuthorities: [b2cPolicies.authorityDomain],
         redirectUri: '/', 
     },
     cache: {
         cacheLocation: BrowserCacheLocation.LocalStorage,
         storeAuthStateInCookie: isIE, 
     },
     system: {
         loggerOptions: {
            loggerCallback: (logLevel, message, containsPii) => {
                console.log(message);
             },
             logLevel: LogLevel.Verbose,
             piiLoggingEnabled: false
         }
     }
 }

export const protectedResources = {
  todoListApi: {
    endpoint: "http://localhost:5000/api/todolist",
    scopes: ["https://your-tenant-name.onmicrosoft.com/api/tasks.read"],
  },
}
export const loginRequest = {
  scopes: []
};

認証ライブラリを起動します

パブリック クライアント アプリケーションは、アプリケーションのシークレットを安全に保持することが信頼されていないため、クライアント シークレットはありません。 src/app フォルダで app.module.ts を開き、次の変更を行います。

  1. MSAL Angular ライブラリと MSAL Browser ライブラリをインポートします。
  2. Azure AD B2C 構成モジュールをインポートします。
  3. HttpClientModuleをインポートします。 HTTP クライアントは、Web API を呼び出すために使用されます。
  4. Angular HTTP インターセプターをインポートします。 MSAL では、インターセプターを使用して、ベアラー トークンを HTTP 承認ヘッダーに挿入します。
  5. 必要な Angular マテリアルを追加します。
  6. 複数アカウントのパブリック クライアント アプリケーション オブジェクトを使用して MSAL をインスタンス化します。 MSAL の初期化には、次のものを渡すことが含まれます。
    1. auth-config.ts の構成オブジェクト。
    2. ルーティング ガードの構成オブジェクト。
    3. MSAL インターセプターの構成オブジェクト。 インターセプター クラスは、既知の保護されたリソースに対して Angular HttpClient クラスを使用する送信要求のトークンを自動的に取得します。
  7. HTTP_INTERCEPTORSMsalGuardAngular プロバイダーを構成します。
  8. MsalRedirectComponent を追加します。

src/app フォルダで app.module.ts を編集し、次のコード スニペットに示す変更を加えます。 変更には、「変更がここから開始」と「変更がここから終了」のフラグが付けられます。

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

/* Changes start here. */
// Import MSAL and MSAL browser libraries. 
import { MsalGuard, MsalInterceptor, MsalModule, MsalRedirectComponent } from '@azure/msal-angular';
import { InteractionType, PublicClientApplication } from '@azure/msal-browser';

// Import the Azure AD B2C configuration 
import { msalConfig, protectedResources } from './auth-config';

// Import the Angular HTTP interceptor. 
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ProfileComponent } from './profile/profile.component';
import { HomeComponent } from './home/home.component';
import { WebapiComponent } from './webapi/webapi.component';

// Add the essential Angular materials.
import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatListModule } from '@angular/material/list';
import { MatTableModule } from '@angular/material/table';
/* Changes end here. */

@NgModule({
  declarations: [
    AppComponent,
    ProfileComponent,
    HomeComponent,
    WebapiComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    /* Changes start here. */
    // Import the following Angular materials. 
    MatButtonModule,
    MatToolbarModule,
    MatListModule,
    MatTableModule,
    // Import the HTTP client. 
    HttpClientModule,

    // Initiate the MSAL library with the MSAL configuration object
    MsalModule.forRoot(new PublicClientApplication(msalConfig),
      {
        // The routing guard configuration. 
        interactionType: InteractionType.Redirect,
        authRequest: {
          scopes: protectedResources.todoListApi.scopes
        }
      },
      {
        // MSAL interceptor configuration.
        // The protected resource mapping maps your web API with the corresponding app scopes. If your code needs to call another web API, add the URI mapping here.
        interactionType: InteractionType.Redirect,
        protectedResourceMap: new Map([
          [protectedResources.todoListApi.endpoint, protectedResources.todoListApi.scopes]
        ])
      })
    /* Changes end here. */
  ],
  providers: [
    /* Changes start here. */
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MsalInterceptor,
      multi: true
    },
    MsalGuard
    /* Changes end here. */
  ],
  bootstrap: [
    AppComponent,
    /* Changes start here. */
    MsalRedirectComponent
    /* Changes end here. */
  ]
})
export class AppModule { }

ルートを構成する

このセクションでは、Angular アプリケーションのルートを設定します。 ユーザーがシングルページアプリケーション内を移動するページ上のリンクを選択するか、アドレスバーにURLを入力すると、ルートはURLをAngularコンポーネントにマップします。 Angular ルーティング の canActivate インターフェイスでは、MSAL Guard を使用して、ユーザーがサインインしているかどうかを確認します。 ユーザーがサインインしていない場合、MSAL はユーザーを Azure AD B2C に連れて行って認証します。

src/app フォルダーで、次のコード スニペットに示されている変更を編集app-routing.module.ts行います。 変更には、「変更がここから開始」と「変更がここから終了」のフラグが付けられます。

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MsalGuard } from '@azure/msal-angular';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { WebapiComponent } from './webapi/webapi.component';

const routes: Routes = [
  /* Changes start here. */
  {
    path: 'profile',
    component: ProfileComponent,
    // The profile component is protected with MSAL Guard.
    canActivate: [MsalGuard]
  },
  {
    path: 'webapi',
    component: WebapiComponent,
    // The profile component is protected with MSAL Guard.
    canActivate: [MsalGuard]
  },
  {
    // The home component allows anonymous access
    path: '',
    component: HomeComponent
  }
  /* Changes end here. */
];


@NgModule({
  /* Changes start here. */
  // Replace the following line with the next one
  //imports: [RouterModule.forRoot(routes)],
  imports: [RouterModule.forRoot(routes, {
    initialNavigation:'enabled'
  })],
  /* Changes end here. */
  exports: [RouterModule]
})
export class AppRoutingModule { }

サインイン ボタンとサインアウト ボタンを追加する

このセクションでは、サインイン ボタンとサインアウト ボタンを アプリ コンポーネントに追加します。 src/app フォルダで app.component.ts ファイルを開き、次の変更を加えます。

  1. 必要なコンポーネントをインポートします。

  2. OnInit メソッドを実装するようにクラスを変更します。 OnInit メソッドは、MSAL MsalBroadcastServiceinProgress$監視可能なイベントをサブスクライブします。 このイベントを使用して、ユーザー操作の状況を把握し、特に対話が完了したことを確認します。

    MSAL アカウント オブジェクトを操作する前に、 InteractionStatus プロパティが InteractionStatus.None を返すことを確認します。 subscribe イベントは、setLoginDisplay メソッドを呼び出して、ユーザーが認証されているかどうかを確認します。

  3. クラス変数を追加します。

  4. 認証フローを開始する login メソッドを追加します。

  5. ユーザーをサインアウトする logout メソッドを追加します。

  6. ユーザーが認証されているかどうかを確認する setLoginDisplay メソッドを追加します。

  7. ngOnDestroy メソッドを追加して、inProgress$サブスクライブ イベントをクリーンアップします。

変更後、コードは次のコード スニペットのようになります。

import { Component, OnInit, Inject } from '@angular/core';
import { MsalService, MsalBroadcastService, MSAL_GUARD_CONFIG, MsalGuardConfiguration } from '@azure/msal-angular';
import { InteractionStatus, RedirectRequest } 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']
})

/* Changes start here. */
export class AppComponent implements OnInit{
  title = 'msal-angular-tutorial';
  loginDisplay = false;
  private readonly _destroying$ = new Subject<void>();

  constructor(@Inject(MSAL_GUARD_CONFIG) private msalGuardConfig: MsalGuardConfiguration, private broadcastService: MsalBroadcastService, private authService: MsalService) { }

  ngOnInit() {

    this.broadcastService.inProgress$
    .pipe(
      filter((status: InteractionStatus) => status === InteractionStatus.None),
      takeUntil(this._destroying$)
    )
    .subscribe(() => {
      this.setLoginDisplay();
    })
  }

  login() {
    if (this.msalGuardConfig.authRequest){
      this.authService.loginRedirect({...this.msalGuardConfig.authRequest} as RedirectRequest);
    } else {
      this.authService.loginRedirect();
    }
  }

  logout() { 
    this.authService.logoutRedirect({
      postLogoutRedirectUri: 'http://localhost:4200'
    });
  }

  setLoginDisplay() {
    this.loginDisplay = this.authService.instance.getAllAccounts().length > 0;
  }

  ngOnDestroy(): void {
    this._destroying$.next(undefined);
    this._destroying$.complete();
  }
  /* Changes end here. */
}

src/app フォルダーで、app.component.html を編集し、次の変更を行います。

  1. プロファイルと Web API コンポーネントへのリンクを追加します。
  2. click イベント属性を login() メソッドに設定したログインボタンを追加します。 このボタンは、 loginDisplay クラス変数が false の場合にのみ表示されます。
  3. click イベント属性を logout() メソッドに設定したログアウトボタンを追加します。 このボタンは、 loginDisplay クラス変数が true の場合にのみ表示されます。
  4. ルーターアウトレット要素を追加します。

変更後、コードは次のコード スニペットのようになります。

<mat-toolbar color="primary">
  <a class="title" href="/">{{ title }}</a>

  <div class="toolbar-spacer"></div>

  <a mat-button [routerLink]="['profile']">Profile</a>
  <a mat-button [routerLink]="['webapi']">Web API</a>

  <button mat-raised-button *ngIf="!loginDisplay" (click)="login()">Login</button>
  <button mat-raised-button *ngIf="loginDisplay" (click)="logout()">Logout</button>

</mat-toolbar>
<div class="container">
  <router-outlet></router-outlet>
</div>

必要に応じて、次の CSS スニペットで app.component.css ファイルを更新します。

.toolbar-spacer {
    flex: 1 1 auto;
  }

  a.title {
    color: white;
  }

アプリのリダイレクトを処理する

MSAL でリダイレクトを使用する場合は、 アプリ リダイレクト ディレクティブを index.htmlに追加する必要があります。 src フォルダーで、次のコード スニペットに示すように index.html を編集します。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MsalAngularTutorial</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
  <!-- Changes start here -->
  <app-redirect></app-redirect>
  <!-- Changes end here -->
</body>
</html>

アプリの CSS を設定する (省略可能)

/src フォルダで、次の CSS スニペットで styles.css ファイルを更新します。

@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';

html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }
.container { margin: 1%; }

ヒント

この時点で、アプリを実行し、サインイン エクスペリエンスをテストできます。 アプリを実行するには、「 Angular アプリケーションの実行 」セクションを参照してください。

ユーザーが認証されているかどうかを確認する

home.component ファイルは、ユーザーが認証されているかどうかを確認する方法を示しています。 src/app/home フォルダで、次のコード スニペットでhome.component.tsを更新します。

コード:

  1. MSAL MsalBroadcastServiceに登録しmsalSubject$、監視可能なイベントを購読しますinProgress$
  2. msalSubject$イベントが認証結果をブラウザコンソールに書き込むことを確認します。
  3. inProgress$ イベントがユーザーが認証されているかどうかを確認します。 getAllAccounts() メソッドは 1 つ以上のオブジェクトを返します。
import { Component, OnInit } from '@angular/core';
import { MsalBroadcastService, MsalService } from '@azure/msal-angular';
import { EventMessage, EventType, InteractionStatus } from '@azure/msal-browser';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  loginDisplay = false;

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

  ngOnInit(): void {
    this.msalBroadcastService.msalSubject$
      .pipe(
        filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),
      )
      .subscribe((result: EventMessage) => {
        console.log(result);
      });

    this.msalBroadcastService.inProgress$
      .pipe(
        filter((status: InteractionStatus) => status === InteractionStatus.None)
      )
      .subscribe(() => {
        this.setLoginDisplay();
      })
  }

  setLoginDisplay() {
    this.loginDisplay = this.authService.instance.getAllAccounts().length > 0;
  }
}

src/app/home フォルダーで、次の HTML スニペットでhome.component.html を更新します。 *ngIf ディレクティブは、loginDisplay クラス変数をチェックして、ウェルカムメッセージを表示または非表示にします。

<div *ngIf="!loginDisplay">
    <p>Please sign-in to see your profile information.</p>
</div>

<div *ngIf="loginDisplay">
    <p>Login successful!</p>
    <p>Request your profile information by clicking Profile above.</p>
</div>

ID トークンの要求を読み取る

profile.component ファイルは、ユーザーの ID トークン要求にアクセスする方法を示しています。 src/app/profile フォルダで、次のコード スニペットでprofile.component.tsを更新します。

コード:

  1. 必要なコンポーネントをインポートします。
  2. MSAL MsalBroadcastService の監視可能イベント inProgress$ をサブスクライブします。 このイベントは、アカウントを読み込み、ID トークン要求を読み取ります。
  3. checkAndSetActiveAccountメソッドがアクティブなアカウントをチェックして設定していることを確認します。 このアクションは、アプリが複数の Azure AD B2C ユーザー フローまたはカスタム ポリシーと対話する場合に一般的です。
  4. getClaims メソッドがアクティブな MSAL アカウント オブジェクトから ID トークン要求を取得することを確認します。 その後、メソッドはクレームを dataSource 配列に追加します。 配列は、コンポーネントのテンプレートバインディングを使用してユーザーにレンダリングされます。
import { Component, OnInit } from '@angular/core';
import { MsalBroadcastService, MsalService } from '@azure/msal-angular';
import { EventMessage, EventType, InteractionStatus } from '@azure/msal-browser';
import { Subject } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})

export class ProfileComponent implements OnInit {
  displayedColumns: string[] = ['claim', 'value'];
  dataSource: Claim[] = [];
  private readonly _destroying$ = new Subject<void>();
  
  constructor(private authService: MsalService, private msalBroadcastService: MsalBroadcastService) { }

  ngOnInit(): void {

    this.msalBroadcastService.inProgress$
      .pipe(
        filter((status: InteractionStatus) =>  status === InteractionStatus.None || status === InteractionStatus.HandleRedirect),
        takeUntil(this._destroying$)
      )
      .subscribe(() => {
        this.checkAndSetActiveAccount();
        this.getClaims(this.authService.instance.getActiveAccount()?.idTokenClaims)
      })
  }

  checkAndSetActiveAccount() {

    let activeAccount = this.authService.instance.getActiveAccount();

    if (!activeAccount && this.authService.instance.getAllAccounts().length > 0) {
      let accounts = this.authService.instance.getAllAccounts();
      this.authService.instance.setActiveAccount(accounts[0]);
    }
  }

  getClaims(claims: any) {

    let list: Claim[]  =  new Array<Claim>();

    Object.keys(claims).forEach(function(k, v){
      
      let c = new Claim()
      c.id = v;
      c.claim = k;
      c.value =  claims ? claims[k]: null;
      list.push(c);
    });
    this.dataSource = list;

  }

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

export class Claim {
  id: number;
  claim: string;
  value: string;
}

src/app/profile フォルダーで、次の HTML スニペットでprofile.component.html を更新します。

<h1>ID token claims:</h1>

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!-- Claim Column -->
  <ng-container matColumnDef="claim">
    <th mat-header-cell *matHeaderCellDef> Claim </th>
    <td mat-cell *matCellDef="let element"> {{element.claim}} </td>
  </ng-container>

  <!-- Value Column -->
  <ng-container matColumnDef="value">
    <th mat-header-cell *matHeaderCellDef> Value </th>
    <td mat-cell *matCellDef="let element"> {{element.value}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

Web API を呼び出す

トークンベースの承認 Web API を呼び出すには、アプリに有効なアクセス トークンが必要です。 MsalInterceptor プロバイダーは、既知の保護されたリソースへの Angular HttpClient クラスを使用する送信要求のトークンを自動的に取得します。

重要

MSAL 初期化メソッド ( app.module.ts クラス内) は、 protectedResourceMap オブジェクトを使用して、Web API などの保護されたリソースを必要なアプリ スコープにマップします。 コードで別の Web API を呼び出す必要がある場合は、Web API URI と Web API HTTP メソッドを、対応するスコープと共に protectedResourceMap オブジェクトに追加します。 詳細については、「 保護されたリソース マップ」を参照してください。

HttpClient オブジェクトが Web API を呼び出すと、MsalInterceptor プロバイダーは次の手順を実行します。

  1. Web API エンドポイントに必要なアクセス許可 (スコープ) を持つアクセス トークンを取得します。

  2. 次の形式を使用して、HTTP 要求の承認ヘッダーでアクセス トークンをベアラー トークンとして渡します。

    Authorization: Bearer <access-token>
    

webapi.component ファイルは、Web API を呼び出す方法を示しています。 src/app/webapi フォルダで、次のコード スニペットで webapi.component.ts を更新します。

コード:

  1. Angular HttpClient クラスを使用して Web API を呼び出します。
  2. auth-config クラスの protectedResources.todoListApi.endpoint 要素を読み取ります。 この要素は、Web API URI を指定します。 Web API URI に基づいて、MSAL インターセプターは対応するスコープを持つアクセス トークンを取得します。
  3. Web API からプロファイルを取得し、 profile クラス変数を設定します。
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { protectedResources } from '../auth-config';

type ProfileType = {
  name?: string
};

@Component({
  selector: 'app-webapi',
  templateUrl: './webapi.component.html',
  styleUrls: ['./webapi.component.css']
})
export class WebapiComponent implements OnInit {
  todoListEndpoint: string = protectedResources.todoListApi.endpoint;
  profile!: ProfileType;

  constructor(
    private http: HttpClient
  ) { }

  ngOnInit() {
    this.getProfile();
  }

  getProfile() {
    this.http.get(this.todoListEndpoint)
      .subscribe(profile => {
        this.profile = profile;
      });
  }
}

src/app/webapi フォルダーで、次の HTML スニペットでwebapi.component.html を更新します。 コンポーネントのテンプレートは、Web API が返す名前をレンダリングします。 ページの下部に、テンプレートによって Web API アドレスが表示されます。

<h1>The web API returns:</h1>
<div>
    <p><strong>Name: </strong> {{profile?.name}}</p>
</div>

<div class="footer-text">
    Web API: {{todoListEndpoint}}
</div>

必要に応じて、次の CSS スニペットで webapi.component.css ファイルを更新します。

.footer-text {
    position: absolute;
    bottom: 50px;
    color: gray;
}

Angular アプリケーションを実行する

次のコマンドを実行します。

npm start

コンソール・ウィンドウには、アプリケーションがホストされているポートの番号が表示されます。

Listening on port 4200...

ヒント

または、 npm start コマンドを実行するには、 Visual Studio Code デバッガーを使用します。 デバッガーは、編集、コンパイル、デバッグのループを高速化するのに役立ちます。

ブラウザーで http://localhost:4200 に移動して、アプリケーションを表示します。

次のステップ