Angular 4 Multiple Guards - 执行顺序

Aku*_*ang 6 angular-routing angular angular-router-guards

我在应用程序中有2个警卫,AuthGuard和AccessGuard.AuthGuard按名称建议保护所有页面,并将会话对象存储在GlobalService中,AccessGuard依赖于AuthGuard在GlobalService中存储的会话对象中的一些访问数据.

当AuthGuard返回Observable然后同时执行AccessGuard以检查尚未到达的会话对象并且代码中断时,会出现问题.有没有其他方法可以限制AccessGuard的执行,直到会话对象到达或任何其他工作来打破这种竞争条件?

#Note我没有将AccessGuard逻辑合并到AuthGuard,因为只有部分路由需要检查才能访问,而所有其他需要身份验证.例如,"用户管理"和"仪表板"之外的所有人都可以访问"帐户"页面和"数据库"页面,这些参数需要来自会话对象的外部访问参数

export const routes: Routes = [
  {
    path: 'login',
    loadChildren: 'app/login/login.module#LoginModule',
  },
  {
    path: 'logout',
    loadChildren: 'app/logout/logout.module#LogoutModule',
  },
  {
    path: 'forget',
    loadChildren: 'app/forget/forget.module#ForgetModule',
  },{
    path: 'reset',
    loadChildren: 'app/reset/reset.module#ResetModule',
  },

    path: 'pages',
    component: Pages,
    children: [
      { path: '', redirectTo: 'db', pathMatch: 'full' },
      { path: 'db', loadChildren: 'app/pages/db/db.module#DbModule' },
      { path: 'bi', loadChildren: 'app/pages/dashboard/dashboard.module#DashboardModule', canActivate:[AccessableGuard] },
      { path: 'account', loadChildren: 'app/pages/account/account.module#AccountModule' },
      { path: 'um', loadChildren: 'app/pages/um/um.module#UserManagementModule', canActivate:[AccessableGuard] },
    ],
    canActivate: [AuthGuard]
  }
];

export const routing: ModuleWithProviders = RouterModule.forChild(routes);
Run Code Online (Sandbox Code Playgroud)

#EDIT:添加保护代码

AuthGuard:

canActivate(route:ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean{
  return new Observable<boolean>( observer => {
    this._dataService.callRestful('POST', params.SERVER.AUTH_URL + urls.AUTH.GET_SESSION).subscribe(
        (accessData) => {
          if (accessData['successful']) {
            observer.next(true);
            observer.complete();
            console.log("done");
          }
          else {
            observer.next(false);
            observer.complete();
          }
        });
  });
}
Run Code Online (Sandbox Code Playgroud)

AccessableGuard:

canActivate(route:ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean{        
if(this._dataService.getModulePermission(route.routeConfig.path.toUpperCase()) < 2){
        return false;
      }
      return true;
    }
Run Code Online (Sandbox Code Playgroud)

#NOTE:_dataService是GlobalService,用于存储AuthGuard的访问权限.

sea*_*ght 9

我选择了一条不同的路径---套入我的守卫并使他们相互依赖。

我有一个RequireAuthenticationGuard和一个RequirePermissionGuard。对于大多数路线,它们都需要同时运行,但是我需要特定的命令。

RequireAuthenticationGuard取决于我authN服务来检查当前会话认证。

RequirePermissionGuard取决于我的authz服务来检查当前会话被授权的路径。

我将添加RequireAuthenticationGuard为的构造函数依赖项,RequirePermissionGuard并且仅在确定了身份验证后才开始检查权限。

require-authentication.guard.ts

constructor(
    private userSessionSerivce: UserSessionService) {}

canActivate(
    _route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
): Observable<boolean> {
    return this.validateAuthentication(state.url);
}
Run Code Online (Sandbox Code Playgroud)

require-permission.guard.ts

constructor(
    private permissionService: PermissionService,
    /**
    * We use the RequireAuthenticationGuard internally
    * since Angular does not provide ordered deterministic guard execution in route definitions
    *
    * We only check permissions once authentication state has been determined
    */
    private requireAuthenticationGuard: RequireAuthenticatedGuard,
) {}

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
): Observable<boolean> {
    const requiredPermissions: Permission[] = next.data.permissions || [];

    return this.requireAuthenticationGuard
        .canActivate(next, state)
        .pipe(
            mapTo(this.validateAuthorization(state.url, requiredPermissions)),
        );
}
Run Code Online (Sandbox Code Playgroud)


pla*_*ter 6

使用Master Guard来启动应用程序保护可以解决问题.

编辑:添加代码片段以便更好地理解.

我遇到了类似的问题,这就是我解决它的方法 -


我们的想法是创建一个主人守卫,并让主控队员处理其他守卫的执行.

路由配置在这种情况下,将包含主卫作为唯一的后卫.

要让主人知道要为特定路线触发的守卫,请在中添加一个data属性Route.

data属性是一个键值对,允许我们使用路径附加数据.

然后可以使用防护中ActivatedRouteSnapshotcanActivate方法参数在防护装置中访问数据.

解决方案看起来很复杂,但一旦将其集成到应用程序中,它将确保防护装置正常工作.

以下示例解释了这种方法 -


1.常量对象来映射所有应用程序保护 -

export const GUARDS = {
    GUARD1: "GUARD1",
    GUARD2: "GUARD2",
    GUARD3: "GUARD3",
    GUARD4: "GUARD4",
}
Run Code Online (Sandbox Code Playgroud)

2.应用防护 -

import { Injectable } from "@angular/core";
import { Guard4DependencyService } from "./guard4dependency";

@Injectable()
export class Guard4 implements CanActivate {
    //A  guard with dependency
    constructor(private _Guard4DependencyService:  Guard4DependencyService) {}

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        return new Promise((resolve: Function, reject: Function) => {
            //logic of guard 4 here
            if (this._Guard4DependencyService.valid()) {
                resolve(true);
            } else {
                reject(false);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

3.路由配置 -

import { Route } from "@angular/router";
import { View1Component } from "./view1";
import { View2Component } from "./view2";
import { MasterGuard, GUARDS } from "./master-guard";
export const routes: Route[] = [
    {
        path: "view1",
        component: View1Component,
        //attach master guard here
        canActivate: [MasterGuard],
        //this is the data object which will be used by 
        //masteer guard to execute guard1 and guard 2
        data: {
            guards: [
                GUARDS.GUARD1,
                GUARDS.GUARD2
            ]
        }
    },
    {
        path: "view2",
        component: View2Component,
        //attach master guard here
        canActivate: [MasterGuard],
        //this is the data object which will be used by 
        //masteer guard to execute guard1, guard 2, guard 3 & guard 4
        data: {
            guards: [
                GUARDS.GUARD1,
                GUARDS.GUARD2,
                GUARDS.GUARD3,
                GUARDS.GUARD4
            ]
        }
    }
];
Run Code Online (Sandbox Code Playgroud)

4.护卫队 -

import { Injectable } from "@angular/core";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router";

//import all the guards in the application
import { Guard1 } from "./guard1";
import { Guard2 } from "./guard2";
import { Guard3 } from "./guard3";
import { Guard4 } from "./guard4";

import { Guard4DependencyService } from "./guard4dependency";

@Injectable()
export class MasterGuard implements CanActivate {

    //you may need to include dependencies of individual guards if specified in guard constructor
    constructor(private _Guard4DependencyService:  Guard4DependencyService) {}

    private route: ActivatedRouteSnapshot;
    private state: RouterStateSnapshot;

    //This method gets triggered when the route is hit
    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {

        this.route = route;
        this.state = state;

        if (!route.data) {
            Promise.resolve(true);
            return;
        }

        //this.route.data.guards is an array of strings set in routing configuration

        if (!this.route.data.guards || !this.route.data.guards.length) {
            Promise.resolve(true);
            return;
        }
        return this.executeGuards();
    }

    //Execute the guards sent in the route data 
    private executeGuards(guardIndex: number = 0): Promise<boolean> {
        return this.activateGuard(this.route.data.guards[guardIndex])
            .then(() => {
                if (guardIndex < this.route.data.guards.length - 1) {
                    return this.executeGuards(guardIndex + 1);
                } else {
                    return Promise.resolve(true);
                }
            })
            .catch(() => {
                return Promise.reject(false);
            });
    }

    //Create an instance of the guard and fire canActivate method returning a promise
    private activateGuard(guardKey: string): Promise<boolean> {

        let guard: Guard1 | Guard2 | Guard3 | Guard4;

        switch (guardKey) {
            case GUARDS.GUARD1:
                guard = new Guard1();
                break;
            case GUARDS.GUARD2:
                guard = new Guard2();
                break;
            case GUARDS.GUARD3:
                guard = new Guard3();
                break;
            case GUARDS.GUARD4:
                guard = new Guard4(this._Guard4DependencyService);
                break;
            default:
                break;
        }
        return guard.canActivate(this.route, this.state);
    }
}
Run Code Online (Sandbox Code Playgroud)

挑战

这种方法的挑战之一是重构现有的路由模型.但是,它可以部分完成,因为更改不会中断.

我希望这有帮助.


小智 3

看看这个 Angular 指南(链接)。“如果您使用的是现实世界的 API,在从服务器返回要显示的数据之前可能会有一些延迟。您不希望在等待数据时显示空白组件。

最好从服务器预取数据,以便在激活路由时就准备好。这还允许您在路由到组件之前处理错误......

总之,您希望延迟渲染路由组件,直到获取所有必要的数据。

你需要一个解析器。”