【发布时间】:2019-08-07 17:17:31
【问题描述】:
我已经有一个 AuthService 可以在登录时对用户进行身份验证,还有一个 AuthGuard 可以在未登录的情况下阻止访问。
我通过 UserProfile/Role 限制访问某些页面,但现在我需要阻止页面上的操作。
我有“管理员、经理、支持和代理”之类的角色,从大到小。
如何将级别仅设置为经理或以上以编辑所有人都可以访问的页面上的内容(支持和代理仅限查看)?
这是我目前的 canActivate 方法:
canActivate(route: ActivatedRouteSnapshot) {
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser) {
// check if route is restricted by role
if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
// role not authorised so redirect to home page
this.router.navigate(['/']);
return false;
}
// authorised so return true
return true;
}
// not logged in so redirect to login page
this.router.navigate(['auth/login']);
return false;
}
这是我的模块 routing.module.ts
const routes: Routes = [{
path: '',
component: ReportsComponent,
canActivateChild: [AuthGuard],
children: [
{
path: 'blocked-users',
component: BlockedUsersComponent,
data: { roles: [Role.admin, Role.manager, Role.suporte, Role.agent] },
children: [
{ ...
需要修复这两个主题:
1) 行data: { roles: [] }我只想通过较低级别(如Agent);
2) 内部组件告诉只有 Manager 可以编辑数据(如果 Role == Support 或 Agent,则只有 disable 一个按钮)
【问题讨论】:
-
您实际上可以做得更好,而不是让它们出现在路线数据中。我建议您创建一个
ngrx-state/service来存储这些信息,然后基于组件中的该状态/一个通用服务包装用于编辑的逻辑,并在路由 gaurd 中重用这些逻辑
标签: angular security angular-guards