Angular-无法获得当前用户的守护角色,以检查他/她是否有权访问受保护的路由

问题描述 投票:0回答:1

我正在尝试在具有多种角色的基于Angular的项目上实现基于角色的访问控制”>

我想在CanActivate界面中获取用户的数据(角色属性),以检查用户是否有权访问routes中受保护的guard,但是BehaviouralSubject在从[ C0]。

因此,我在身份验证服务中获取用户的数据,然后将接收到的值传递给API主题,但将属性更新为(BehaviouralSubject)在防护文件中不可用。

认证服务

userRole

Auth Guard

    constructor() {
      let localToken: string
      if (localStorage.getItem('token')) {
        localToken = localStorage.getItem('token')
        this.getUserInfo(localToken)
      }
    }
      userRole = new BehaviorSubject(null)
      userRole$ = this.userRole.asObservable()    

      // called in constructor of a auth. service (every time when user called) 
      // and after login as well, so user's data always available. 
      getUserInfo(data) {
          this.requestService
            .post('GET_USER_INFO', data)
            .subscribe((response: ILoggedInUser) => {
               // data from API {email: "[email protected]", userName: "ccc", role: "viewer"}
               this.userRole.next(response.user)  
            })
        }

这里是路由

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

      return this.authService.userRole$.pipe(
        map(member => {
          if (member) {
            // check if route is restricted by role
            if (
              route.data.roles &&
              route.data.roles.indexOf(member.role) === -1
            ) {
              // role not authorised so redirect to home page
              this.router.navigate(['/login'])
              return false
            }

          return true
          } else {
            this.router.navigate(['/login'])
            return false
          }
        }),
      )
    }

[我也尝试了另一种方法(例如,使用订阅),但是当我尝试像这样从 const routes: Routes = [ { path: 'home', component: HomeComponent, }, { path: 'admin', component: AdminComponent, canActivate: [AuthGuard], data: { roles: ['admin'] }, }, { path: 'editor', component: EditorsComponent, canActivate: [AuthGuard], data: { roles: ['admin', 'editor'} }, { path: 'viewer', component: ViewersComponent, canActivate: [AuthGuard], data: { roles: ['admin', 'viewer'] }, } ] subscribe主题时:

userRole

然后有一个无法将类型'AuthGuard'中的属性'canActivate'分配给基本类型'CanActivate'中的相同属性

错误,因为 return this.authService.userRole.subscribe((member) => { ....... ....... } 类型不能分配给Subscription类型。

因此,您能否提供任何提示或建议使用可观察变量处理[​​C0]中<< RBAC

的更好方法。 P.S。

我已经看到booleanangular,但是我不想在那里保留用户数据(令牌除外)。

我试图在基于角的项目上实现基于角色的访问控制,在该项目中,我想在CanActivate接口中获取用户数据(角色属性)以检查......>

angular observable rbac behaviorsubject angular-guards
1个回答
0
投票
问题在于,solutions可观察的元素最初会发出localStorage,因为它已订阅到userRole userRole$,后者将null作为参数。
© www.soinside.com 2019 - 2024. All rights reserved.