我已经将 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
}])