我正在尝试以角度为我的应用程序进行基于角色的访问,我需要一些帮助,因为我是角度的新手......
\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\nprivate 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
accessLoginToken(token: string) {\n const check = …
Run Code Online (Sandbox Code Playgroud) role-base-authorization typescript role-based-access-control angular auth-guard