首页 > 解决方案 > 获取 BrowserAuthError:interaction_in_progress:交互当前正在进行中

问题描述

您好,我有一个支持“所有 Microsoft 帐户用户”的应用程序注册。我尝试使用 3 种类型的登录帐户从我的 Angular 应用程序登录。

>     1. Microsoft tenant users - Successfully logging-in
>     2. Microsoft Personal account users i.e. hotmail/outlook.com accounts - Successfully logging-in
>     3. Other organization accounts. - Getting BrowserAuthError: interaction_in_progress: Interaction is currently in progress

在此处输入图像描述

    Inside app.module.ts file
        const isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 || window.navigator.userAgent.indexOf("Trident/") > -1; // Remove this line to use Angular Universal
        export function loggerCallback(logLevel: LogLevel, message: string) {
          //console.log(message);
        }
        export function MSALInstanceFactory(): IPublicClientApplication {
          return new PublicClientApplication({
            auth: {
        
              clientId: authConfig.clientId,
              authority: authConfig.authority,
              redirectUri: authConfig.redirectUri,
            },
            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(authConfig.graphEndpoint, ['user.read']);
          protectedResourceMap.set('https://graph.microsoft.com/v1.0/me', ['user.read']);
        
          protectedResourceMap.set(`${environment.API_URL}*/*`, authConfig.consentScopes);
        
          return {
            interactionType: InteractionType.Redirect,
            protectedResourceMap
          };
        }
        
        export function MSALGuardConfigFactory(): MsalGuardConfiguration {
          return {
            interactionType: InteractionType.Redirect,
            authRequest: {
              scopes: ['user.read']
            }//,
            //loginFailedRoute: '/login-failed'
          };
        }

async ngOnInit(): Promise<void> {
    this.isIframe = window !== window.parent && !window.opener; // Remove this line to use Angular Universal
    this.setLoginDisplay();

    this.msalBroadcastService.inProgress$
      .pipe(
        filter((status: InteractionStatus) => status === InteractionStatus.None),
        takeUntil(this._destroying$)
      )
      .subscribe(() => {
        this.setLoginDisplay();
        this.checkAndSetActiveAccount();
      })
     
  }
  checkAndSetActiveAccount(){
    /**
     * If no active account set but there are accounts signed in, sets first account to active account
     * To use active account set here, subscribe to inProgress$ first in your component
     * Note: Basic usage demonstrated. Your app may require more complicated account selection logic
     */
    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]);
    }
  }

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

  loginPopup() {
    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);
      });
    }
  }

  logout(popup?: boolean) {
    if (popup) {
      this.authService.logoutPopup({
        mainWindowRedirectUri: "/"
      });
    } else {
      this.authService.logoutRedirect();
    }
  }

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

Inside app.component.ts file

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

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

checkAndSetActiveAccount(){
    /**
     * If no active account set but there are accounts signed in, sets first account to active account
 

    * To use active account set here, subscribe to inProgress$ first in your component
     * Note: Basic usage demonstrated. Your app may require more complicated account selection logic
     */
    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]);
    }
  }

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

  loginPopup() {
    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);
      });
    }
  }

  

    logout(popup?: boolean) {
        if (popup) {
          this.authService.logoutPopup({
            mainWindowRedirectUri: "/"
          });
        } else {
          this.authService.logoutRedirect();
        }
      }
    
      ngOnDestroy(): void {
        this._destroying$.next(undefined);
        this._destroying$.complete();
      }
    
      setLoginDisplay() {
        this.loginDisplay = this.authService.instance.getAllAccounts().length > 0;
      }

我们使用相同的配置,并且所有登录身份验证的一切都相同。但仅对于组织帐户,它会显示此错误。请提供建议,因为我是 Angular 身份验证的新手

标签: angularauthenticationmsal

解决方案


由于以下代码,您会收到此错误: msalInstance.loginRedirect(loginRequest);

这段代码将检查会话存储中是否存在重定向过程所需的键和其他临时值,如果值存在且值相等,那么它将通过异常interaction_in_progress

尝试将代码设置为如下所示:

// authRedir.ts
await msalInstance.handleRedirectPromise();


// mySignInPage.ts (or userprofile.vue, or whatever page invokes a sign-in)
await msalInstance.handleRedirectPromise();

async signIn(){
const loginRequest: msal.RedirectRequest = {
scopes: ["openid", "profile", "offline_access","your_other_scopes"]
redirectUri: "http://localhost:8080/authredirect"
 };

 const accounts = msalInstance.getAllAccounts();
  if (accounts.length === 0) {


  await msalInstance.loginRedirect();
  }
}

请记住在您的应用中调用它时验证所有异步/等待。


推荐阅读