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

Angular升级至v12后OIDC配置失效无法跳转登录页求助

Angular v12升级后OIDC配置失效问题解决

问题描述

将Angular版本升级至v12后,OIDC配置无法正常工作,无法跳转至登录页,控制台报错:

main.js:1 Uncaught TypeError: Cannot read properties of undefined (reading 'init')

错误原因

当前实现的oidcConfiguration函数存在两个核心问题:

  1. 仅声明了commonService变量但未通过依赖注入获取实例,直接调用init()时变量处于未定义状态
  2. AuthModule.forRoot在模块初始化阶段立即执行,此时APP_INITIALIZER还未完成配置文件的加载,无法动态获取OIDC参数

解决方案

恢复并适配v11版本的工厂函数初始化方式,确保配置加载完成后再初始化OIDC服务,同时兼容v12的API变化:

修改app.module.ts配置

  1. 删除当前的oidcConfiguration函数,恢复并更新原注释的工厂函数:
export function oidcConfigServiceFactory(
  oidcConfigService: OidcConfigService,
  commonService: CommonService
) {
  return async () => {
    await commonService.init();
    const config = commonService.getAppConfig().oidcConfig;
    return oidcConfigService.withConfigs({
      authority: config?.stsServer,
      authWellknownEndpointUrl: config?.authWellknownEndpoint, // 适配v12参数名变更
      redirectUrl: window.location.origin,
      clientId: config?.clientId,
      scope: `${config?.scope} offline_access`,
      responseType: 'code',
      triggerAuthorizationResultEvent: true,
      postLogoutRedirectUri: `${window.location.origin}/unauthorized`,
      startCheckSession: false,
      silentRenew: true,
      silentRenewUrl: window.location.origin + '/silent-renew.html',
      postLoginRoute: '/home',
      forbiddenRoute: '/forbidden',
      unauthorizedRoute: '/unauthorized',
      logLevel: LogLevel.Warn,
      historyCleanupOff: true,
      useRefreshToken: true,
      autoUserInfo: false, // 参数名从autoUserinfo改为驼峰式autoUserInfo
      renewTimeBeforeTokenExpiresInSeconds: 60,
      maxIdTokenIatOffsetAllowedInSeconds: 600,
      ignoreNonceAfterRefresh: true,
    });
  };
}
  1. 修改AuthModule.forRoot的配置,改为空配置占位,由工厂函数完成后续初始化:
AuthModule.forRoot({
  config: {} // 留空,通过工厂函数动态注入配置
}),
  1. 保持APP_INITIALIZER的配置不变,确保工厂函数被正确注入执行:
{
  provide: APP_INITIALIZER,
  useFactory: oidcConfigServiceFactory,
  deps: [OidcConfigService, CommonService],
  multi: true,
},

关键注意点

  • 确认CommonService已在模块的providers数组中注册(当前代码已满足)
  • 适配angular-auth-oidc-client版本升级后的参数名变更:autoUserinfo→autoUserInfo、authWellknownEndpoint→authWellknownEndpointUrl

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 09:49:56