简体   繁体   中英

Angular 2 router canActivate Auth Guard

I've been searching for this for last 4 hours and couldn't find any answers.

I have several Authguards written, and i want to be able to tell router that if some of them are true it should give permission, but angular 2 router checks if every guard is true and then gives permission, otherwise it will block the link, is there any good way of doing this? i could write several Authentication guards but i don't think thats a good idea.

for example i want the /profile page to be accessible by admin and super-user, but i don't want the regular-user to access /profile page

You can inject your guards in one parent Guard and take the control yourself:

    @Injectable()
    class Guard implements CanActivate {

      constructor(private guard1: Guard1, private guard2: Guard2) {}

      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):boolean {
        // I'm assuming that your guard1.canActivate and guard2.canActivate return boolean
        return guard1.canActivate() || guard2.canActivate();
      }
    }

In your route config use only Guard guard:

{
  path : 'route',
  canActivate : Guard 
  ...
}

and of course you can use guard1 and guard2 in other routes.

You can use CanLoad interface in your authentication guard. For example let's say your route is just like that;

{
     path: 'profile',
     component: 'ProfileComponent',
     canLoad: [
          AuthenticationGuard
     ]
}

In your AuthenticationGuard , implement CanLoad interface. If user has no permission for this link, modules for this route would not be loaded.

export class AuthenticationGuard implements CanLoad {
     canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
          //in here ask your authentication service to check current user has permission for this route
     }
}

I hope it helps, please let me know for further questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM