Angular Route Guards:或者vs.和

Nat*_*oss 3 roles typescript angular-routing angular angular-route-guards

我正在努力使用路线保护来保护我的Angular应用程序的前端.在过去与他们合作并在线研究时,为路由添加多个防护要求所有这些防护返回true以允许访问.

但是如果我只想让一个返回true以允许访问呢?(比如||而不是&&)

例如,我的路线保护在用户的令牌中查找某些角色:

@Injectable()
export class ActiveRoleGuard implements CanActivate {
    constructor(private sessionService: SessionService, private router: Router) { }


    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let token = this.sessionService.getToken();

        if (!token) {
             return false;
        }

        if (token.role.toLowerCase().indexOf("active") < 0) {
            this.router.navigate(["/issue"]);
            return false;
        }

        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

@Injectable()
export class AdminRoleGuard implements CanActivate {
    constructor(private sessionService: SessionService, private router: Router) { }


    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let token = this.appSessionService.getToken();

        if (!token) {
            return false;
        }

        if (token.role.toLowerCase().indexOf("admin") < 0) {
            this.router.navigate(["/issue"]);
            return false;
        }

        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我在路由器模块中将它们正常组合,那就像......

{path: "someroute", component: SomeComponent, canActivate: [ActiveRouteGuard, AdminRouteGuard]}

......但这需要用户既ActiveAdmin.但是,如果我想执行是Active任何一个Admin 一个Manager

像这样在API上执行很简单:

[Authorize(Roles = "Active")]
[Authorize(Roles = "Admin, Manager")]
public class SomeController : ApiController
Run Code Online (Sandbox Code Playgroud)

但我如何在Angular中做到这一点?

Kir*_*kin 7

CanActivate您可以只使用可以"配置"的单个版本,而不是使用两个单独的实现.为此,您可以利用data酒店的财产Route.例如,在您的路线中,您可以执行以下操作:

{
    path: "someroute",
    component: SomeComponent,
    canActivate: [RoleRouteGuard],
    data: {
        requiredRoles: ["Role1", "Role2", "Role3"]
    }
}
Run Code Online (Sandbox Code Playgroud)

使用它,您可以采用现有的一个CanActivate实现,并使其更通用.您可以访问requiredRoles从属性data通过ActivatedRouteSnapshot.例如:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const requiredRoles = route.data.requiredRoles;
    ....
Run Code Online (Sandbox Code Playgroud)

一旦你有了这个,你可以检查令牌的角色是否在数组等等.

如果您有一个始终需要的Active角色,然后是一个Admin或一个Manager角色,您也可以将其扩展为具有多个data属性.例如,您可以拥有requiredRolesatLeastOneOfRoles更新您的逻辑以相应地处理...此时有很多选项,但我认为您不需要帮助.

  • @NathanFoss你可以在这种情况下使用枚举. (2认同)