Angular2 routing canActivate and AuthGuard (JWT) with user role parameter

You can set the data parameter of the route with the role like this

const appRoutes: Routes = [
  path: 'account/super-secure', 
  component: SuperSecureComponent, 
  canActivate: [RoleGuard], 
  data: { roles: ['super-admin', 'admin'] } 

and then have this in canActivate of RoleGuard:

canActivate(route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {

    let roles =["roles"] as Array<string>;
    return (roles == null || roles.indexOf("the-logged-user-role") != -1);

I think this could be another way of doing it instead of creating guard for every role. I would actually take this rout since it requires less code and handles the problem very nicely.

Leave a Comment