【问题标题】:AuthGuard canActivate with http request for rolesAuthGuard 可以通过 http 请求角色激活
【发布时间】:2018-06-15 19:59:35
【问题描述】:

我有一个奇怪的情况。我的 AuthGuard 比平时更复杂。 这取决于身份验证令牌 + 用户角色。

因此,每当 canActivate 被触发时,我必须检查用户是否已通过身份验证,然后检查他是否有权前往所需的路线。

权限检查在后端处理,所以我只需要发出请求并获得响应,无论用户是否被允许。

我不知道如何实现这一点。检查身份验证令牌很容易,但是如何将其与 http 请求结合起来呢?我不知道。我尝试了很多解决方案,但总是出现错误或无限等待。

这是我的 canActivate 方法的代码。注意checkPermissionhttp.get(...)

canActivate(route: ActivatedRouteSnapshot, routerState: RouterStateSnapshot) {

    return this.store.select('auth').pipe(
      take(1),
      map((state: State) => {
        if (state.token) {
          return this.checkPermission(state, route).pipe(
            map(res => {
              if (res) {
                return true;
              }
              return false;
            })
          );
        } else {
          return false;
        }
      }));
  }

【问题讨论】:

  • 我猜this.checkPermission(state, route) 正在返回 observable,在这种情况下你应该使用 switchMap 而不是主管道内的 map
  • @GogaKoreli 我试过了,但是有错误,比如 e.lift 不是函数
  • 抛出该确切错误的源代码行是什么?
  • @GogaKoreli 请看一下 Narek 的回答
  • 顺便请注意,你做这件事的方式在意识形态上是不正确的。我的意思是,您在每个 canActivate 上向后端发送请求对于客户端和后端来说都非常繁重。您应该获取权限列表并在本地检查客户端导航权限。不要以为我在回避你的问题,我只是在建议更好的架构。

标签: javascript angular rxjs


【解决方案1】:

使用 switchMap

canActivate(route: ActivatedRouteSnapshot, routerState: RouterStateSnapshot) {

    return this.store.select('auth').pipe(
      take(1),
      switchMap((state: State) => {
        if (state.token) {
          return this.checkPermission(state, route);
        } else {
          return of(false);
        }
      }),
      map(res => !!res)
    );
  }

【讨论】:

  • 我得到 main.dd7f4d98ff8e78017d91.js:formatted:15730 错误错误:未捕获(承诺):TypeError:e.lift 不是函数
  • 我不知道堆栈跟踪很奇怪
猜你喜欢
  • 1970-01-01
  • 2017-12-15
  • 1970-01-01
  • 2015-01-08
  • 1970-01-01
  • 2012-02-14
  • 2015-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多