在 MSAL Angular 中使用重定向

在 MSAL 中使用重定向时,必须使用 MsalRedirectComponenthandleRedirectObservable 之一来处理重定向

请注意,下面添加了有关将 MSAL Angular 与 Angular 独立组件配合使用的特定指南。

  1. MsalRedirectComponent
  2. handleRedirectObservable手动订阅
  3. 使用独立组件进行重定向

1. MsalRedirectComponent:专用 handleRedirectObservable 组件

注释

此方法与 Angular 独立组件不兼容。 有关 使用独立组件的重定向 部分,请参阅下面的进一步指导。

这是用于处理重定向的建议方法:

  • @azure/msal-angular 提供可导入到应用程序的专用重定向组件。 我们建议导入 MsalRedirectComponent 并在 app.module.ts 上与 AppComponent 一起引导,因为这将处理所有重定向,而无需你的组件手动订阅 handleRedirectObservable()
  • 希望在重定向后执行功能的页面(例如用户帐户功能、UI 更改等)应订阅 inProgress$ 可观察对象,并筛选 InteractionStatus.None。 这将确保在执行函数时没有正在进行的交互。 注意,订阅 inProgress$ 可观察对象时,最后一个/最近的 InteractionStatus 也可用。 有关检测交互的更多信息,请参阅我们的事件文档。
  • 如果您不想使用MsalRedirectComponent,则必须按照下面的方法,使用handleRedirectObservable()自行处理重定向。
  • 有关此方法的示例,请参阅 Angular 模块示例

msal.redirect.component.ts

// This component is part of @azure/msal-angular and can be imported and bootstrapped
import { Component, OnInit } from "@angular/core";
import { MsalService } from "./msal.service.ts";

@Component({
  selector: 'app-redirect', // Selector to be added to index.html
  template: ''
})
export class MsalRedirectComponent implements OnInit {
  
  constructor(private authService: MsalService) { }
  
  ngOnInit(): void {    
      this.authService.handleRedirectObservable().subscribe();
  }
  
}

index.html

<body>
  <app-root></app-root>
  <app-redirect></app-redirect> <!-- Selector for additional bootstrapped component -->
</body>

app.module.ts

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

import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatListModule } from '@angular/material/list';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
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'; // Redirect component imported from msal-angular

export function loggerCallback(logLevel: LogLevel, message: string) {
  console.log(message);
}

export function MSALInstanceFactory(): IPublicClientApplication {
  return new PublicClientApplication({
    auth: {
      clientId: '00001111-aaaa-2222-bbbb-3333cccc4444',
      redirectUri: 'http://localhost:4200',
      postLogoutRedirectUri: 'http://localhost:4200'
    },
    cache: {
      cacheLocation: BrowserCacheLocation.LocalStorage,
    },
    system: {
      loggerOptions: {
        loggerCallback,
        logLevel: LogLevel.Info,
        piiLoggingEnabled: false
      }
    }
  });
}

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
  };
}

export function MSALGuardConfigFactory(): MsalGuardConfiguration {
  return { interactionType: InteractionType.Redirect };
}

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    ProfileComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    MatButtonModule,
    MatToolbarModule,
    MatListModule,
    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] // Redirect component bootstrapped here
})
export class AppModule { }

app.component.ts

import { Component, OnInit, Inject, OnDestroy } from '@angular/core';
import { MsalBroadcastService, InteractionStatus } from '@azure/msal-angular';
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(
        filter((status: InteractionStatus) => status === InteractionStatus.None),
        takeUntil(this._destroying$)
      )
      .subscribe(() => {
        // Do user account/UI functions here
      })
  }

2. 手动订阅 handleRedirectObservable

这不是我们推荐的方法,但如果你无法引导 MsalRedirectComponent,则必须使用 handleRedirectObservable 处理重定向,如下所示:

  • handleRedirectObservable() 应在可能发生重定向的每个页上订阅。 受 MSAL Guard 保护的页面不需要订阅 handleRedirectObservable(),因为重定向是在 Guard 中处理的。
  • handleRedirectObservable() 完成之前,不应访问用户账户或执行任何相关操作,因为在此之前其内容可能尚未完全加载。 此外,如果在 handleRedirectObservables() 进行期间调用交互式 API,将导致 interaction_in_progress 错误。 有关如何检查交互的更多信息,请参阅我们的事件文档;有关interaction_in_progress错误的详细信息,请参阅我们的错误文档。
  • 有关此方法的示例,请参阅 MSAL Angular 模块示例

home.component.ts文件的示例:

import { Component, OnInit } from '@angular/core';
import { MsalBroadcastService, MsalService } from '@azure/msal-angular';
import { AuthenticationResult } from '@azure/msal-browser';

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

  constructor(private authService: MsalService) { }

  ngOnInit(): void {
    this.authService.handleRedirectObservable().subscribe({
      next: (result: AuthenticationResult) => {
        // Perform actions related to user accounts here
      },
      error: (error) => console.log(error)
    });
  }

}

handleRedirectObservable 选项

handleRedirectObservable 接受具有以下属性的可选 HandleRedirectPromiseOptions 对象:

财产 类型 Description
hash string 要处理的可选哈希,而不是当前 URL 哈希。
navigateToLoginRequestUrl boolean 是否在处理重定向后导航到原始请求 URL。 默认值为 true. 如果您想自行处理导航,请将其设置为 false

示例用法:

// Basic usage - processes redirect and navigates to original URL
this.authService.handleRedirectObservable().subscribe();

// Disable automatic navigation after redirect
this.authService.handleRedirectObservable({ navigateToLoginRequestUrl: false }).subscribe({
  next: (result: AuthenticationResult) => {
    if (result) {
      // Handle navigation yourself
      this.router.navigate(['/home']);
    }
  }
});

// Process a specific hash
this.authService.handleRedirectObservable({ hash: '#code=...' }).subscribe();

注释

直接将哈希字符串传递给 handleRedirectObservable(hash) 已被弃用。 请改用 options 对象: handleRedirectObservable({ hash: "#..." }).

3. 使用独立组件的重定向

由于许多使用独立组件的 Angular 应用程序无法引导 MsalRedirectComponent,因此必须直接订阅 handleRedirectObservable。 建议在 app.component.ts 文件中进行订阅。

  • 根据应用程序体系结构,你可能还需在其他领域订阅 handleRedirectObservable()
  • 检查是否存在正在进行的交互仍然适用;有关如何检查交互的更多信息,请参阅我们关于 事件 的文档。
  • 有关此方法的示例,请参阅我们的 Angular standalone 示例

app.component.ts文件示例:

import { Component, OnInit, Inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { MsalService, MsalBroadcastService, MSAL_GUARD_CONFIG, MsalGuardConfiguration } from '@azure/msal-angular';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    standalone: true,
    imports: [CommonModule, RouterModule]
})
export class AppComponent implements OnInit {

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

  ngOnInit(): void {
    this.authService.handleRedirectObservable().subscribe();
  }
}