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

前端 未结 3 1251
半阙折子戏
半阙折子戏 2020-12-13 03:33

In this exaple project with JWT authentication we se how to allow only authenticated users to some route:

import { RouterConfig } from \'@angular/router\';
i         


        
3条回答
  •  既然无缘
    2020-12-13 04:39

    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 = route.data["roles"] as Array;
        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.

提交回复
热议问题