You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure B2C改密码流程点击取消后Angular应用报错的处理咨询

解决Azure B2C改密码流程取消操作后的Angular路由错误问题

问题场景

已在Azure B2C中实现自定义策略入门包的PasswordChange策略,用户完成改密码流程可正常跳转回Angular应用,但点击取消选项时,应用出现运行时错误,无法像注册/登录流程那样捕获错误并执行跳转处理。

报错信息

路由匹配错误

main.ts:6 ERROR Error: Uncaught (in promise): Error: NG04002: Cannot match any routes. 
URL Segment: 'login-failed'
Error: NG04002: Cannot match any routes. URL Segment: 'login-failed'
   at ApplyRedirects.noMatchError (router.mjs:3656:16)
  at router.mjs:3638:28
  at catchError.js:10:39

MSAL服务错误

core.mjs:8400 ERROR ServerError: access_denied: AADB2C90091: The user has cancelled 
entering self-asserted information.
Correlation ID: 931f36f0-640e-461b-84c0-3c4fa0ea04c0
Timestamp: 2023-11-03 03:24:59Z

at ResponseHandler.validateServerAuthorizationCodeResponse (ResponseHandler.mjs:76:19)
at AuthorizationCodeClient.handleFragmentResponse (AuthorizationCodeClient.mjs:83:25)

现有代码

改密码触发逻辑

changePassword() {
  this.authService.loginRedirect({
    authority: environment.b2cPolicies.authorities.changePassword.authority,
    scopes: environment.apiConfig.scopes
  });
}

现有错误监听逻辑(注册/重置密码流程可用)

// Listen for error events
this.msalBroadcastService.msalSubject$
  .pipe(filter((msg: any) => msg.eventType === EventType.LOGIN_FAILURE),
    tap((msg: any) => {
      const error = msg.error as InteractionRequiredAuthError;
     
      if (error && error.errorMessage && error.errorMessage.includes('AADB2C90091')) {
         // Redirect to login page. User has cancelled self-asserted or change password.
         
        this.authService.instance.loginRedirect();
      }
      else if (error && error.errorMessage && 
         error.errorMessage.includes('AADB2C90118')) {
        // Trigger the Password Reset user journey
        this.authService.loginRedirect({
          authority: environment.b2cPolicies.authorities.resetPassword.authority,
          scopes: environment.apiConfig.scopes
        });
      }
    })
  )
  .subscribe();

解决方案

1. 配置login-failed路由,解决路由匹配错误

在Angular路由配置文件(如app-routing.module.ts)中添加路由规则,捕获B2C重定向的login-failed路径:

const routes: Routes = [
  // 其他现有路由
  {
    path: 'login-failed',
    redirectTo: '/login', // 直接跳转到登录页或指定页面
    pathMatch: 'full'
  }
];

2. 完善MSAL错误监听逻辑,覆盖改密码流程事件

修改监听代码,确保捕获改密码流程可能触发的错误事件,并处理用户取消操作:

import { EMPTY } from 'rxjs';
import { ServerError } from '@azure/msal-browser';

// 监听MSAL事件
this.msalBroadcastService.msalSubject$
  .pipe(
    filter((msg: any) => 
      msg.eventType === EventType.LOGIN_FAILURE || 
      msg.eventType === EventType.ACQUIRE_TOKEN_FAILURE // 改密码流程可能触发此事件
    ),
    tap((msg: any) => {
      const error = msg.error as ServerError;
      
      if (error?.errorMessage?.includes('AADB2C90091')) {
        // 用户取消操作,跳转到登录页
        this.router.navigate(['/login']).catch(err => console.error(err));
      }
      else if (error?.errorMessage?.includes('AADB2C90118')) {
        // 触发重置密码流程
        this.authService.loginRedirect({
          authority: environment.b2cPolicies.authorities.resetPassword.authority,
          scopes: environment.apiConfig.scopes
        });
      }
    }),
    catchError(err => {
      console.error('MSAL事件处理错误:', err);
      return EMPTY;
    })
  )
  .subscribe();

3. 优化Azure B2C自定义策略的取消跳转配置

在自定义策略的SelfAssertedPage技术配置文件中,修改取消按钮的跳转地址,直接指向Angular应用的登录页,避免生成login-failed路径:

<ClaimsProvider>
  <DisplayName>Local Account Password Change</DisplayName>
  <TechnicalProfiles>
    <TechnicalProfile Id="SelfAsserted-ChangePassword">
      <DisplayName>Change Password</DisplayName>
      <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      <Metadata>
        <!-- 其他元数据配置 -->
        <Item Key="CancelButtonReturnUrl">https://your-angular-app-domain.com/login</Item>
        <Item Key="CancelButtonTarget">_self</Item>
      </Metadata>
      <!-- 其他配置项 -->
    </TechnicalProfile>
  </TechnicalProfiles>
</ClaimsProvider>

内容的提问来源于stack exchange,提问作者Choco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:16:35