首页 > 解决方案 > 与 keycloak 集成时,组件在 canActivate 返回角度 4 之前加载

问题描述

我已经将 keycloak 与应用程序集成,我已经编写了 AuthGuard 来保护特定的路由。canActivate 工作正常,但是路由的组件也会加载,另一个 API 调用也会在后台触发。如何加载组件直到 canActivate 返回结果。

AuthGuard:
-----------
 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    if (!this.keycloakService.getIsClientSecretKeyFetch()) {
      this.errorHandler._enlivenErrorhandler.handleError({"status":"401","message" :"Unable to get client details. Please contact your administrator ","url":window.location.href});
      this.router.navigate(['404'], { queryParams: { tenantId: this.cookieService.get('tenantId') } });
    }
    this.isAccessAllowed(route,state);
    return super.canActivate(route, state);
  }

  isAccessAllowed(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    return new Promise((resolve, reject) => {
      if (!this.authenticated) {
        this.keycloakAngular.login();
        return;
      }
      const path = route.data.path;
      this.keycloakService.isAuthorized(path).then(
        (res) => {
          let access = res;
          if (access) {
            resolve(true);
          } else {
            resolve(false);
          }
        });
      resolve(true);
    });
  }

routes.ts
-----------
RouterModule.forChild([

            {
                path: 'data-source-mongo-list',
                canActivate: [AppAuthGuard],
                data: {
                    path:'data-source-mongo-list'
                },
                component: DataSourceListComponent
            }])

标签: angularkeycloakauth-guard

解决方案


在我看来,您似乎自己实现了所有 OpenId 的东西。根据我的个人经验,我不能推荐这个。您是否尝试使用 angular-oauth2-oidc?我认为这里描述得很好:https ://www.softwarearchitekt.at/post/2016/07/03/authentication-in-angular-2-with-oauth2-oidc-and-guards-for-the-newest-新路由器-英文-version.aspx


推荐阅读