我一直在尋找這最後4個小時,並找不到任何答案。角2路由器canActivate身份驗證警衛
我有幾個Authguards寫的,我想告訴路由器,如果其中一些是真的,它應該給予許可,但角2路由器檢查每個守衛是否爲真,然後給予許可,否則它會阻止鏈接,有沒有這樣做的好方法?我可以寫幾個認證衛士,但我認爲這不是一個好主意。
例如我想/profile
頁是由管理員和超級用戶訪問,但我不希望普通用戶訪問/profile
頁
我一直在尋找這最後4個小時,並找不到任何答案。角2路由器canActivate身份驗證警衛
我有幾個Authguards寫的,我想告訴路由器,如果其中一些是真的,它應該給予許可,但角2路由器檢查每個守衛是否爲真,然後給予許可,否則它會阻止鏈接,有沒有這樣做的好方法?我可以寫幾個認證衛士,但我認爲這不是一個好主意。
例如我想/profile
頁是由管理員和超級用戶訪問,但我不希望普通用戶訪問/profile
頁
你可以注入你的警衛在一個父衛隊,並採取控制自己:
@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
...
}
,當然你可以在其他路線中使用guard1
和guard2
。
您可以在身份驗證警衛中使用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
}
}
我希望它可以幫助,請讓我知道進一步的問題。
你可以使用guard來做這個例子,例如檢查即將到來的用戶是admin,SU然後返回true,否則返回true,否則你可以邏輯處理它 –