简体   繁体   中英

AuthGuard canActivate with http request for roles

I have a strange situation. My AuthGuard is more complicated than usual. It's depending on authentication token + on user role.

So whenever canActivate is fired I have to check if the user is authenticated and then check if he has a permission to go to the route it wants.

Permission checking is handled in backend so I'm only have to make request and get response, whether the user is permitted or no.

I don't know how to achieve this. Checking auth token is easy, but how to combine this with http request? I don't know. I tried many solutions, but always I get error or infinity waiting.

Here is my code for canActivate method. Note that checkPermission is http.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;
        }
      }));
  }

use 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)
    );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM