【问题标题】:How can I correctly implement an Angular Guard?如何正确实现 Angular Guard?
【发布时间】:2020-09-24 16:17:38
【问题描述】:

我正在实施一个有角度的 AdmingGuard 来保护一些路由。

管理员警卫:

  // --------------ADMIN GUARD
  
  // want protect routes from user who are not Admin
  canActivate(): boolean {
    // isLogged() service method: set 2 global boolean variable in teh service:
    //- 'isLogged'= true if the user is logged in
    //- 'adminLoggedIn' = true if the logged user is an Admin
    this.authService.isLogged();

    // getIsAdminLogged() service method: return value of global var 'adminLoggedIn'
    const adminLoggedIn = this.authService.getIsAdminLogged();

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

服务:

// SERVICE 

  //here global variable:
  loggedIn: boolean; // the user is logged ?
  adminLoggedIn: boolean; // the logged user is an Admin ?

  constructor(private http: HttpClient, private router: Router) {}

  // this makes an Http Request to the server sending the AccessToken
  // and control if the user that sent the AccesToken is logged and if is an Admin
  isLogged() {

    // get the AccessToken from localStorage, if is empty: im sure the user is not logged
    const accessToken = this.getAccessToken;
    if (typeof accessToken === 'undefined' || accessToken === null) {
      this.loggedIn = false;
      this.adminLoggedIn = false;
      return;
    }

    // here makes the https ruquest to the server 
    return this.http
      .get<any>(this.isLoggedUrl)
      .pipe(catchError(this.errorHandler))
      .subscribe(
        (res) => {

          // server send back the 'res' response 
          // control in the 'res' if the user is logged and if the user is an Admin
          // in base on this controls, set the 2 global var 'loggedIn' and 'adminLoggedIn'

          if (res.status == 200) {
            this.loggedIn = true;
            if (res.userType == 'admin') {
              this.adminLoggedIn = true;
            }
          } else {
            this.adminLoggedIn = false;
          }
        },
        (err) => {

          // server sand back some error
          // control if the error is 'TokenExpiredError' (in that case try to refresh the tokens)
          // otherwise set the 2 vars 'loggedIn' and 'adminLoggedIn' to false

          if (err.error.message == 'TokenExpiredError') {
            const refreshToken = this.getRefreshToken;
            if (typeof refreshToken === 'undefined' || refreshToken === null) {
              this.loggedIn = false;
              this.adminLoggedIn = false;
            } else {
              // refresh tokens if possible
              // also this method set the var 'loggedIn' and 'adminLoggedIn'
              this.refreshTokens();
            }
          } else {
            this.loggedIn = false;
            this.adminLoggedIn = false;
          }
        }
      );
  }

   // return the value of the global var 'adminLoggedIn'. 
  getIsAdminLogged() {
    return this.adminLoggedIn;
  }

问题是

按照它应该执行的 CanActivate 中的语句顺序:

  • isLogged();在 isLogged() 内部执行 HTTP 请求以验证用户是否已登录以及用户是否为管理员。所以将服务 2 全局变量 'loggedIn' 和 'adminLoggedIn' 中的 isLogged() 设置为 true 或 false。
  • getIsAdminLogged();获取 'adminLoggedIn' 的值来检查登录的用户是否是管理员(这个 Guard 的目标)

但是 HTTP 请求不是异步的,所以 getIsAdminLogged();在该 HTTP 请求验证用户是否为管理员之前执行。

我已经阅读了一些关于它的解决方案,但我仍然感到困惑。

谢谢

【问题讨论】:

    标签: angular http observable angular-router-guards


    【解决方案1】:

    盲目更改所有代码,如果有问题请告诉我

    管理员警卫

    async canActivate(): boolean {
    
        this.authService.tokenValid()
    
        let that = this
    
        await this.authService.isLogged().then(res => {
          if (res.status == 200) {
            that.authService.setStatusUser(true)
            if (res.userType == 'admin') {
              that.authService.setStatusUser(true)
            }
          } else {
            that.authService.setStatusAdmin(false)
          }
        }).catch(err => {
          if (err.error.message == 'TokenExpiredError') {
            that.authService.setRefresh()
          } else {
            that.authService.setError()
          }
        });
    
        // getIsAdminLogged() service method: return value of global var 'adminLoggedIn'
        const adminLoggedIn = this.authService.getIsAdminLogged();
    
        if (adminLoggedIn) {
          return true;
        } else {
          this.router.navigate(['/login']);
          return false;
        }
      }
    
    

    服务

    import 'rxjs/add/operator/toPromise';
    
    ...some code ...
    
    setStatusAdmin(status: boolean){
        this.adminLoggedIn = status;
      }
    
      setStatusUser(status: boolean){
        this.loggedIn = status
      }
    
      setError(){
        this.loggedIn = false;
        this.adminLoggedIn = false;
      }
    
      setRefresh(){
        const refreshToken = this.getRefreshToken;
        if (typeof refreshToken === 'undefined' || refreshToken === null) {
          this.loggedIn = false;
          this.adminLoggedIn = false;
        } else {
          // refresh tokens if possible
          // also this method set the var 'loggedIn' and 'adminLoggedIn'
          this.refreshTokens();
        }
      }
    
      tokenValid(){
        const accessToken = this.getAccessToken;
        if (typeof accessToken === 'undefined' || accessToken === null) {
          this.loggedIn = false;
          this.adminLoggedIn = false;
        }
      }
    
      isLogged(): Promise<any> {
        return this.http
          .get<any>(this.isLoggedUrl)
          .pipe(catchError(this.errorHandler)).toPromise()
      }
    
    

    【讨论】:

    • await this.authService.isLogged().toPromise(); 这给了我一个错误:'Promise'toPromise' does not exist on type 'Subscription'' 和async canActivate(): boolean { 并给我:'异步函数或方法的返回类型必须是全局 Promise 类型。你的意思是写'Promise'吗? '
    • 哦,你返回一个订阅......这是一个不好的做法。等我改写答案。
    • 请检查代码,盲目改一切,可能有错误...告诉我是否缺少什么。
    • THX Derek.. 我会尽快检查它,同时,我会理解是否有某种方法可以解决它,保持 Observable(而不是在 Promise 中转换)
    • 欢迎您。 Observable 的问题是你想等待响应吗……是为了对 Promise 进行解析。
    【解决方案2】:
     loggedIn: boolean;
    

    而不是将布尔值赋值为“null”

     loggedIn:null
    

    在保护文件中this.authService.getIsAdminLogged() 将返回 observable。 Guard 将等到这个 observable 处于“完成”状态。在管理员保护文件中,返回这个:

    import { take, skipWhile, tap } from 'rxjs/operators';
    
    //http service returns observable
    return this.authService.getIsAdminLogged().pipe(
          skipWhile((value) => value === null),
          // if the value is null, we are not getting any value, we are getting either false or true and faking that this observable is complete
          // before u were getting false by default. the issue was while app component checking for authentication, guard would consider that it was false, maybe 1 second later it gets the answe as true
          // to prevent this issue we are giving the final result to the guard
          take(1),
          //tap() does not modify the incoming value
          tap((authenticated) => {
            if (!authenticated) {
              this.router.navigateByUrl('/');
            }
          })
        );
    

    【讨论】:

    • 感谢答案,但不是很清楚 skipWhile 和 take 和 tap 是如何工作的......
    猜你喜欢
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    相关资源
    最近更新 更多