简体   繁体   中英

Component is loading before canActivate returns the result in angular 4 when integrated with keycloak

I have integrated keycloak with application, I have written AuthGuard to protect specific routes.canActivate works fine but the component for the route also loading and another API calls also getting triggered in background. How to load component until canActivate returns the result.

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
            }])

From what I see it looks like you implemented all that OpenId stuff by yourself. From my personal experience I can't recommend this. Did you try to use angular-oauth2-oidc? I think it is well described here: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM