小编Rac*_*rta的帖子

在 Angular 中 -> 如何使用基于角色的访问将角色保存在数据库中来检查用户是否具有权限

我正在尝试以角度为我的应用程序进行基于角色的访问,我需要一些帮助,因为我是角度的新手......

\n\n

首先,这是我在路线中确定哪些角色可以访问它的内容......

\n\n

来自 app-routing.module.ts

\n\n
{\n  path: 'profile',\n  component: ComunityComponent,\n  canActivate: [AuthGuard],\n  data: {\n    allowedRoles: ['admin', 'user']\n  }\n},\n
Run Code Online (Sandbox Code Playgroud)\n\n

其次,我使用 canActivate 函数来检查用户是否可以访问该路由。\n来自 auth.guard.ts

\n\n
private hasAccess: boolean;\n\nconstructor(private router: Router, private auth: AuthService) {}\n\ncanActivate(next: ActivatedRouteSnapshot,\n              state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {\n    const allowedRoles = next.data.allowedRoles;\n    if (localStorage.getItem('currentUser')) {\n      return this.checkAccess(localStorage.getItem('currentUser'), allowedRoles);\n    }\n\n    this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});\n    return false;\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

第三,我开发了 accessLoginToken 函数,它将通过 httpclient.get 服务查找登录用户的角色,该服务返回一个包含分配给用户的角色的数组。例子{success: true, roles:['user']}\n来自 auth.service.ts

\n\n
 accessLoginToken(token: string) {\n    const check = …
Run Code Online (Sandbox Code Playgroud)

role-base-authorization typescript role-based-access-control angular auth-guard

6
推荐指数
1
解决办法
1万
查看次数