2017-03-16 118 views
0

我一直在寻找这最后4个小时,并找不到任何答案。角2路由器canActivate身份验证警卫

我有几个Authguards写的,我想告诉路由器,如果其中一些是真的,它应该给予许可,但角2路由器检查每个守卫是否为真,然后给予许可,否则它会阻止链接,有没有这样做的好方法?我可以写几个认证卫士,但我认为这不是一个好主意。

例如我想/profile页是由管理员和超级用户访问,但我不希望普通用户访问/profile

+0

你可以使用guard来做这个例子,例如检查即将到来的用户是admin,SU然后返回true,否则返回true,否则你可以逻辑处理它 –

回答

1

你可以注入你的警卫在一个父卫队,并采取控制自己:

@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(); 
     } 
    } 

在你的路线配置只使用Guard后卫:

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

,当然你可以在其他路线中使用guard1guard2

1

您可以在身份验证警卫中使用CanLoad接口。例如,让我们说你的路线就是这样的;

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

在你AuthenticationGuard,实现CanLoad接口。如果用户没有此链接的权限,则不会加载此路由的模块。

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 
    } 
} 

我希望它可以帮助,请让我知道进一步的问题。