与keycloak集成时,canActivate在角度4中返回结果之前组件正在加载

时间:2019-02-26 13:37:13

标签: angular keycloak auth-guard

我已经将密钥斗篷与应用程序集成在一起,我编写了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
            }])

1 个答案:

答案 0 :(得分:0)

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