12

In my project I have two guards. AuthGuard and PermissionGuard. I need to first AuthGuard runs and when it resolved and if true the permissionGuard begins but now this guards are running parallel and permissionGuard not working well. the way I used for this issue is that I called the AuthGuard CanActivate method in Permission guard but I think there is a quite better way for doing this.

Hossein Ahmadi
  • 839
  • 2
  • 11
  • 24
  • Maybe [this answer](http://stackoverflow.com/a/40590812/6942210) can help you. I think he has the same problem. – Philipp Kief Dec 23 '16 at 12:41
  • thanks, the answer of question you mentioned is same way I did but as I said I think that better way maybe exists. – Hossein Ahmadi Dec 23 '16 at 12:48
  • @hosseinahmadi. Do you still need help with this? – AngularChef Feb 23 '17 at 14:42
  • That answer duplicates the existing guard. Can we pass the instance of the other guard into the new one? – Jeff May 10 '17 at 01:29
  • Does this answer your question? [Multiple canActivate guards all run when first fails](https://stackoverflow.com/questions/40589878/multiple-canactivate-guards-all-run-when-first-fails) – planet_hunter Nov 25 '19 at 10:02

3 Answers3

1

The best way I've seen it done is to expose the router guards on child routes. Here is a working example.

{
  path:'', canActivate:[AuthorizationService1], 
    children: [
      {
        path:'', canActivate:[AuthorizationService2],component: HomeComponent
      }
    ]
}
C.OG
  • 6,236
  • 3
  • 20
  • 38
zmanc
  • 5,201
  • 12
  • 45
  • 90
0

guards can't really depend on each other unfortunately. you can do as another person suggested and make one on the parent route and one on a child route, or My preference is just to make a third guard that runs both checks on it's own sequentially so I don't need to muddy up my routes, assuming they're implemented as observables:

@Injectable({ providedIn: 'root' })
export class AuthAndPermissionGuard implements CanActivate {
  constructor(private authGuard: AuthGuard, permGuard: PermGuard) { }
  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.authGuard.canActivate(next, state).pipe(
      switchMap(isAuthed => isAuthed ? this.permGuard.canActivate(next, state) : of(false))
    );
  }
}
bryan60
  • 28,215
  • 4
  • 48
  • 65
0

you can esaly pass two gurd to routes like this :

{
   path:'', canActivate:[AuthorizationGuards1,AuthorizationGuards2] 
}

after AuthorizationGuards1 success AuthorizationGuards2 activated, the relation between these two guard is st like AuthorizationGuards1 && AuthorizationGuards2 conditions.

Amir Dora.
  • 2,831
  • 4
  • 40
  • 61
farokh veician
  • 224
  • 2
  • 10