0

我正在使用路线将用户重定向到允许的视图。但是没有权限的用户可以通过在地址栏中提供 path[route] 来路由到它。

我尝试使用 auth-guard,但使用它会导致我进入一个连续循环,即 /[somePath] 触发 canActivate 并检查权限,并在解析路由后再次进入 auth-guard,因为 canActivate 存在于所有路由中。

下面是一段代码[我试过的] -

app.routing.ts

{
    path: '',
    component: A,
    canActivate: [AuthGuard]
},
{
    path: 'B',
    component: B,
    canActivate: [AuthGuard]
},
{
    path: 'C',
    component: C,
    canActivate: [AuthGuard]
},
{
    path: 'D',
    component: D,
    canActivate: [AuthGuard]
},
{
    path: 'E',
    component: E,
    canActivate: [AuthGuard]
}

auth-guard.ts

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

if (this.ck.getUser()) {
    // check if route is restricted by role
    if(this.ck.hasRealmRole('A')){
      this.router.navigate(['/A']);
      return false;
    }
    if(this.ck.hasRealmRole('B')){
      this.router.navigate(['/B']);
      return false;
    }
    if(this.ck.hasRealmRole('C')){
      this.router.navigate(['/C']);
      return false;
    }

    if(this.ck.hasRealmRole('D')){
      this.router.navigate(['/D']);
      return false;
    }

    return true;
}


return false;

}

请帮助我了解如何限制用户导航到不允许他们访问的视图。

4

0 回答 0