0

我正在尝试阻止非管理员用户访问管理仪表板本身。为此,如果令牌有效,我必须检查后端,如果有效,则用户实际上是管理员。我似乎能够阻止它,但我不知道如何在 Angular 11 的 AuthGuard 中等待 API 调用?我必须使 canActivate() 方法异步还是什么?

身份验证服务:

  // This method works and returns an Observable<boolean>
  public hasUserRole(theAccessToken: string, userRole: string): Observable<any> {
    const httpOptions = {
      headers: new HttpHeaders({
        accessToken: theAccessToken,
        requiredUserRole: userRole,
      })
    };
    return this.http.get<any>(Constants.API_ENDPOINT_GET_USER_ROLES, httpOptions);
  }

  // This method, I don't know how to implement... I tried .pipe and .tap and whatnot but I can't get anything to wait for the API call to finish.
  public isLoggedInAndHasUserRole(token: string, userRole: string): boolean {
      // return this.hasUserRole(token, userRole); // TODO: How to wait for this API call? .map doesn't seem to work in Angular11 and I can't get the .pipe() to work either.
  }

Auth Guard(有效,但我不知道如何等待 API 调用):

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const token = this.commonService.getToken();

    if (token !== '' && token !== undefined) {

      if (this.authenticationService.isLoggedInAndHasUserRole(token, 'Admin')) {
<snip for brevity>

带有 API 结果的图像 在此处输入图像描述

4

1 回答 1

2

canActivate 有几个返回值。你可以返回Observable<boolean>,auth 守卫只有在那个 observable 被解决后才会继续。

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> {
    const token = this.commonService.getToken();

    if (token !== '' && token !== undefined) {
        return this.authenticationService.isLoggedInAndHasUserRole(token, 'Admin').pipe(
        map((hasRole) => {
            if (hasRole) {
                return true;
            } else {
                this.commonService.navigateToHome();
                return false; //
            }
        }));
    } else {
       this.commonService.navigateToLogin();
       return false;
    }
}

在您的授权服务中:

 public isLoggedInAndHasUserRole(token: string, userRole: string): Observable<boolean> {
      return this.hasUserRole(token, userRole);
  }
于 2021-01-31T19:01:54.713 回答