首页 > 解决方案 > 角基本后卫

问题描述

可以使用角色 args 创建守卫吗?

我想要这样的东西:

  {
    path: 'app1',
    loadChildren: 'src/app/app1/app1.module#App1Module',
    canActivate: [new Guard ([Role.Admin, Role.app1])]
  }

和激活功能:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const user = this.authenticationService.user;
    if (user &&
        user.roles &&
        user.roles.some((role) => this.roles.includes(role))) {
        return true;
    }
}

标签: angular

解决方案


我们接下来要做的是,实现两个 Guards AuthGuard(启用 API 身份验证)和 CleanGuard(禁用身份验证)。

现在,在app-routing.module.ts. 我们可以更灵活地为特定的 API 集启用身份验证,而有些则不启用。

const routes: Routes = [
  { path: 'pages', canActivate: [AuthGuard], loadChildren: 'app/pages/pages.module#PagesModule' },
  {
    path: 'auth',
    component: JGAuthComponent,
    canActivate: [CleanGuard],
    children: [
      {
        path: '',
        component: LoginComponent,
      },
  { path: '', redirectTo: 'pages', pathMatch: 'full' },
  { path: '**', redirectTo: 'pages' },
];

清洁卫士

@Injectable()
export class CleanGuard implements CanActivate {
  constructor(private authService: AuthService,
    private router: Router,
    private tokenService: JGTokenService) {
  }

  canActivate(): Observable<boolean> {
    this.tokenService.clear();
    return observableOf(true);
  }
}

AuthGuard

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,
    private router: Router) {
  }

  canActivate(): Observable<boolean> {
    return this.authService.isAuthenticated()
      .pipe(
        tap(authenticated => {
          if (!authenticated) {
            this.router.navigate(['auth/login']);
          }
        }),
        catchError((d) => {
          this.router.navigate(['auth/login']);
          return observableOf(false);
        }),
      )
  }
}

推荐阅读