【问题标题】:Any guard activation for route activation路由激活的任何保护激活
【发布时间】:2019-12-15 02:04:51
【问题描述】:

我正在尝试在我的 Angular 应用程序中实现防护。到目前为止,我已经设置了 3 个守卫,但我希望将它们设置为 OR 或 ANY 模式,如果任何守卫允许请求,则可以激活路由。

有人有办法吗?

我的守卫很简单,三个看起来都一样:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { AppSettings } from './AppSettings';

@Injectable({ providedIn: 'root' })
export class GuardianGuard implements CanActivate {
    constructor(
        private router: Router,
        private http: HttpClient
    ) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
        //Get the users role from the API based on the JWT they were authenticated with
        return this.http.get(`${AppSettings.API_ENDPOINT}/Role`).pipe(map(data => {
            //Check if the returned server role is that of the guardian
            if (data === "3") {
                //Allow the action if it is
                return true;
            } else {
                //Return to login and deny action if it is not
                this.router.navigate(['/login']);
                return false;
            }
        }));
    }
}

【问题讨论】:

  • 为什么不使用 3 种方法在服务中移动警卫内部的逻辑,然后使用这 3 种方法在相同的 gaurd put 或条件中移动
  • 如果成功验证,您还可以让每个守卫在导航中添加一个数据对象。然后每个守卫将检查该数据对象,并自动验证任何先前经过身份验证的请求。

标签: angular


【解决方案1】:

你可以有一个通用的 3 种方法,每个 gaurd 的激活逻辑类似于

export class YourService(){

firstCondition(){
//return boolean
}

secondCondition(){
//return boolean
}

thirdCondtion(){
//return boolean
}

}

然后创建另一个具有类似逻辑的 gaurd

 canActivate(){
  return yourServiceRef.FirstCondition() || yourServiceRef.SecondCondition()....
 } 

此外,您可以使用相同的服务与您的老警卫调用相应的方法;

【讨论】:

  • 这意味着我需要为我的身份验证角色的每个组合创建一个身份验证保护。有没有办法创建一个可以将我的身份验证保护作为构造函数参数的类,然后根据它激活正确的保护?
  • @Tachyon 在这种情况下,您可以在路由器的数据参数中传递 gaurdtype,并且可以在您的 gaurd stackoverflow.com/a/42721468/5621827 中进行逻辑实现
猜你喜欢
  • 1970-01-01
  • 2019-03-06
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 2019-07-16
  • 2011-08-26
  • 2021-07-27
相关资源
最近更新 更多