Angular 11 : Problem at Msal Angular V2 package

标签 angular azure msal-angular

我已将我的 Angular 项目从 v8 升级到 v11。 我已将 @azure/msal-angular 包从 V1 升级到 V2(2.0.0-beta.3)。 我已按照 https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-angular-v2-samples/angular11-sample-app 上给出的示例进行操作.

在 Azure 门户上完成的配置在早期版本中运行良好。这是一个 SSO 应用程序,没有登录按钮。

  1. 应用程序模块

    const isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 || 
     window.navigator.userAgent.indexOf("Trident/") > -1;  
    
     export function loggerCallback(logLevel: LogLevel, message: string) {
       console.log(message);
     }
    
     export function MSALInstanceFactory(): IPublicClientApplication {
      return new PublicClientApplication({
       auth: {
              clientId: environment.clientId,
              authority: 
              `https://login.microsoftonline.com/${environment.tenantName}`,
               redirectUri: environment.redirectUrl
             },
      cache: {
              cacheLocation: BrowserCacheLocation.LocalStorage,
              storeAuthStateInCookie: isIE, 
             },
     system: {
       loggerOptions: {
                 loggerCallback,
                 logLevel: LogLevel.Info,
                 piiLoggingEnabled: false
                }
          }
       });
     }
    
     export function MSALInterceptorConfigFactory(): 
      MsalInterceptorConfiguration {
         const protectedResourceMap = new Map<string, Array<string>>();
         protectedResourceMap.set(`${environment.clientId}`, 
         [`${environment.scopeUrl}`]);
    
      return {
         interactionType: InteractionType.Redirect,
         protectedResourceMap
       };
     }
    
    export function MSALGuardConfigFactory(): MsalGuardConfiguration {
       return {
         interactionType: InteractionType.Redirect,
         authRequest: {
           scopes: [`${environment.scopeUrl}`]
        },
       };
      }
    
     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
     },
    

应用程序组件

ngOnInit(){

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



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

  }

  checkAccount() {
    this.loggedIn = this.authService.instance.getAllAccounts().length > 0;
  }

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

  login() {
    if (this.msalGuardConfig.interactionType === InteractionType.Popup) {
      if (this.msalGuardConfig.authRequest) {
        this.authService.loginPopup({ ...this.msalGuardConfig.authRequest } as PopupRequest)
          .subscribe((response: AuthenticationResult) => {
            this.authService.instance.setActiveAccount(response.account);
          });
      } else {
        this.authService.loginPopup()
          .subscribe((response: AuthenticationResult) => {
            this.authService.instance.setActiveAccount(response.account);
          });
      }
    } else {
      if (this.msalGuardConfig.authRequest) {
        this.authService.loginRedirect({ ...this.msalGuardConfig.authRequest } as RedirectRequest);
      } else {
        this.authService.loginRedirect();
      }
    }
  }

环境

scopeUrl: "api://xxxxxxx-xxxx-xxxx-a247-6023a95xxxxx/api",
  clientId: "b4f868f3-xxxx-xxxx-xxxx-4d44f053ff29",
  tenantName: "83993965-xxxx-xxxx-xxxx-d8259608fd30",
  scope: "user.read",
  appUrl: "http://localhost:4300/",
  location: "localStorage",
  graphUrl: "https://graph.microsoft.com/v1.0/me"

但现在相同的配置不适用于升级后的 msal 包。 我遇到以下错误

http 后调用:

https://login.microsoftonline.com/83993965-e753-xxxx-xxxx-d825960xxxx/oauth2/v2.0/token

错误响应:

error_codes: [7000218]
error_description: "AADSTS7000218: The request body must contain the following parameter: 'client_assertion' or 'client_secret'.
↵Trace ID: f0843107-bd57-4d08-b92e-15a873724e00
↵Correlation ID: 1764d345-xxxx-xxx-xxxx-20a9fda5bcb6
↵Timestamp: 2021-04-14 12:58:22Z"
error_uri: "https://login.microsoftonline.com/error?code=7000218"

感谢任何帮助

最佳答案

如果您要在 Angular 项目中从 msal V1 升级到 V2。您必须在 Azure AD 中执行相同的操作。我删除了 Azure 目录中当前的 Azure 应用程序 ID,并按照下面的 MS 文档中提到的过程为 MSAL 2.0 创建了一个新的应用程序 ID。

注册 Azure AD 并设置 allowPublicClient= true https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-spa-app-registration

注意:使用模板“单页应用程序”创建新的应用程序 ID。检查 list 中 redirectUri 的类型是“Spa”而不是“Web”。如果存在“Web”,则将其删除。

关于 Angular 11 : Problem at Msal Angular V2 package,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67092304/

相关文章:

Angular 2在更改路线时保留服务实例

angular - 如何编写 Angular2 npm 模块 - Angular2 RC 6

Azure - 部署已在使用 - 如何将辅助角色和 Web 角色发布到同一托管服务

用于容器和 AppSettings/环境变量的 Azure WebApps

azure-active-directory - 访问 token 版本错误(预期为 V2,收到了 V1)

javascript - 带有重定向的 Angular 2 AuthGuard 服务?

node.js - 使用 Angular 和 NodeMailer 发送电子邮件

Azure 数据工厂 - if 条件表达式生成器

javascript - Angular 13 - BrowserAuthError : interaction_in_progress: Interaction is currently in progress