【发布时间】: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