从 2.16.0 升级后,MSAL 3.0 未返回 Angular 17 中的帐户

问题描述 投票:0回答:1

我最近在 Angular 17 项目中将

@azure/msal-angular
@azure/msal-browser
从版本 2.16.0 升级到 3.0.0。自升级以来,我无法使用
this.authService.instance.getAllAccounts()
检索用户帐户,它现在返回一个空数组

import { MsalService, MsalBroadcastService, MSAL_GUARD_CONFIG, MsalGuardConfiguration } from '@azure/msal-angular';

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



 async ngOnInit() {
    this.msalBroadcastService.inProgress$
    .pipe(
      filter((status: InteractionStatus) => status === InteractionStatus.None),
      takeUntil(this._destroying$)
    )
    .subscribe(() => {
      this.setLoginDisplay();
    }, (error) => {
      this.isLoading = false;
    });
  }

async setLoginDisplay() {
  if (!this.localAuthService.isLogin) {
    this.loginDisplay = this.authService.instance.getAllAccounts().length > 0;
    if (this.loginDisplay) {
      const data = this.authService.instance.getAllAccounts()[0];
      // Further processing...
    }
  }
}

控制台中没有出现任何错误,除了库升级之外,配置和初始化似乎没有变化。我怀疑这可能是 Angular 17 中 MSAL 3.0 的生命周期或配置问题。是否有人遇到过类似问题或知道 MSAL 3.0 中可能影响帐户检索的任何重大更改?

azure azure-ad-msal msal-angular
1个回答
0
投票

使用以下代码成功登录后,我能够获取用户帐户详细信息。

代码:

src/app/auth.service.ts:

import { Injectable } from '@angular/core';
import { PublicClientApplication, AuthError, AccountInfo } from '@azure/msal-browser';
import { msalConfig } from './auth-config';
import { MsalService } from '@azure/msal-angular';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  private app: PublicClientApplication;
  private isMsalInitialized: boolean = false;

  constructor(private msalService: MsalService) {
    this.app = new PublicClientApplication(msalConfig);
    this.initializeMsal();
  }
  private async initializeMsal(): Promise<void> {
    try {
      await this.app.initialize();
      await this.app.handleRedirectPromise();
      this.isMsalInitialized = true; 
    } catch (error) {
      console.error('MSAL initialization error:', error);
    }
  }
  async login(): Promise<void> {
    if (!this.isMsalInitialized) {
      await this.initializeMsal();
    }
    try {
      const loginResponse = await this.app.loginPopup({
        scopes: ['openid', 'profile', 'User.Read'],
      });
      console.log('Login successful', loginResponse);
    } catch (error) {
      if (error instanceof AuthError) {
        console.error('Authentication error:', error.errorMessage);
      } else {
        console.error('Unexpected error during login:', error);
      }
    }
  }
  logout(): void {
    this.app.logout();
  }
  async getUserAccounts(): Promise<AccountInfo[] | null> {
    if (!this.isMsalInitialized) {
      await this.initializeMsal();
    }
    try {
      const accounts = await this.msalService.instance.getAllAccounts();
      return accounts;
    } catch (error) {
      console.error('Error retrieving accounts:', error);
      return null;
    }
  }
}

src/app/sso/sso.component.ts:

import { Component } from '@angular/core';
import { AuthService } from '../../auth.service';
import { AccountInfo } from '@azure/msal-browser';

@Component({
  selector: 'app-sso',
  templateUrl: './sso.component.html',
  styleUrls: ['./sso.component.css'],
})
export class SsoComponent {
  userAccounts: AccountInfo[] | null = null;
  constructor(private authService: AuthService) {}
  async ngOnInit() {
    this.userAccounts = await this.authService.getUserAccounts();
  }
  login(): void {
    this.authService.login();
  }
  logout(): void {
    this.authService.logout();
  }
}

auth-config.ts:

export const msalConfig = {
    auth: {
      clientId: '<client_ID>',
      authority: 'https://login.microsoftonline.com/<tenant_ID>',
      redirectUri: 'http://localhost:4200',
    },
    cache: {
      cacheLocation: 'localStorage',
      storeAuthStateInCookie: true,
    },
  };

我在Azure AD身份验证中添加了以下URL作为单页应用程序,如下所示:

http://localhost:4200

enter image description here

输出:

enter image description here

浏览器输出:

enter image description here

enter image description here

我成功登录并收到了我的帐户详细信息,如下所示。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.