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

Angular14中angular-auth-oidc-client新标签页自动登录重定向异常

Angular 14 angular-auth-oidc-client 新标签页自动登录重定向异常问题

使用库

angular-auth-oidc-client

场景

用户已在应用主标签页登录,打开新标签页直接访问特定页面(如my-account):

  • 预期行为:自动登录完成后,重定向至请求的my-account页面
  • 实际行为:跳转回首页,无法到达目标页面,影响体验

问题

  1. 如何正确配置AutoLoginPartialRoutesGuard实现自动登录后的精准重定向?
  2. 是否有其他配置或方案可解决该问题?

已尝试使用AutoLoginPartialRoutesGuard但未生效,需正确配置守卫或其他可行方案。


现有代码

路由文件

RouterModule.forRoot([
  {
    path: '',
    canActivate: [AuthorizationGuard],
    component: MainComponent,
    children: [
      {
        path: '',
        redirectTo: 'overview',
        pathMatch: 'full'
      },
      {
        path: 'orders',
        loadChildren: () => import('./modules/orders/orders.module').then(m => m.OrdersModule),
        canActivate: [AutoLoginPartialRoutesGuard],
      },
      {
        path: '**',
        redirectTo: ''
      }
    ]
  }
], {
  useHash: environment.hashRouting,
  scrollPositionRestoration: 'enabled'
})

认证配置

export const httpLoaderFactory = () => {

  const authOptions$: Observable<OpenIdConfiguration> = config$.pipe(
    map((authOptions: AuthOptions) => {
      return {
        authority: authOptions.authEndpoint,
        redirectUrl: 'https://localhost:3000',
        postLogoutRedirectUri: 'https://localhost:3000',
        clientId: authOptions.spaClientId,
        scope: 'openid profile offline_access',
        responseType: 'code',
        secureRoutes: [authOptions.apiEndpoint, authOptions.authEndpoint],
        silentRenew: true,
        useRefreshToken: true,
        ignoreNonceAfterRefresh: true,
        automaticSilentRenew: true,
        disableIdTokenValidation: true,
        autoUserInfo: false
      } as OpenIdConfiguration;
    })
  );
  return new StsConfigHttpLoader(authOptions$);
};

认证守卫

export class AuthorizationGuard implements CanActivate {

  constructor(private authService: AuthService) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
    return this.authService.isAuthorized().pipe(
      map(isAuthorized => {
        if (!isAuthorized) this.authService.authorize();
        return isAuthorized;
      })
    );
  }
}

解决方案

1. 正确配置AutoLoginPartialRoutesGuard

你的路由中仅给orders路由添加了AutoLoginPartialRoutesGuard,而主路由使用自定义AuthorizationGuard,导致其他受保护路由无法触发自动登录重定向逻辑,需调整守卫层级:

方案1:全局替换主路由守卫

将主路由的AuthorizationGuard替换为AutoLoginPartialRoutesGuard,让所有子路由都继承自动登录重定向能力:

RouterModule.forRoot([
  {
    path: '',
    canActivate: [AutoLoginPartialRoutesGuard], // 替换为官方守卫
    component: MainComponent,
    children: [
      {
        path: '',
        redirectTo: 'overview',
        pathMatch: 'full'
      },
      {
        path: 'orders',
        loadChildren: () => import('./modules/orders/orders.module').then(m => m.OrdersModule),
      },
      {
        path: 'my-account',
        loadChildren: () => import('./modules/my-account/my-account.module').then(m => m.MyAccountModule),
      },
      {
        path: '**',
        redirectTo: ''
      }
    ]
  }
], {
  useHash: environment.hashRouting,
  scrollPositionRestoration: 'enabled'
})

方案2:自定义守卫集成官方逻辑

若需保留AuthorizationGuard的额外校验逻辑,可注入AutoLoginPartialRoutesGuard并复用其重定向逻辑:

import { AutoLoginPartialRoutesGuard } from 'angular-auth-oidc-client';
import { switchMap, of } from 'rxjs';

export class AuthorizationGuard implements CanActivate {

  constructor(
    private authService: AuthService,
    private autoLoginGuard: AutoLoginPartialRoutesGuard
  ) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> {
    return this.authService.isAuthorized().pipe(
      switchMap(isAuthorized => {
        if (isAuthorized) return of(true);
        // 调用官方守卫处理自动登录及重定向
        return this.autoLoginGuard.canActivate(route, state);
      })
    );
  }
}

2. 优化认证配置

动态设置redirectUrl

将固定的redirectUrl改为动态获取当前页面URL,确保重定向回原请求路径:

return {
  // ...其他配置
  redirectUrl: window.location.origin + window.location.pathname,
} as OpenIdConfiguration;

启用授权结果事件

添加triggerAuthorizationResultEvent: true配置,确保自动登录完成后触发路由重定向事件:

return {
  // ...其他配置
  triggerAuthorizationResultEvent: true,
} as OpenIdConfiguration;

3. 自定义守卫中传入目标URL

在调用authorize()时,传入当前请求的URL作为重定向目标:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> {
  return this.authService.isAuthorized().pipe(
    map(isAuthorized => {
      if (!isAuthorized) {
        this.authService.authorize({
          customParams: { redirect_uri: state.url }
        });
        return false;
      }
      return isAuthorized;
    })
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 13:05:27