是否可以使用角色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;
}
}
答案 0 :(得分:0)
不确定默认的Angular保护器,但是是的,有一个很棒的软件包可供使用-
这可以让您保护路由器以及模板的某些部分,例如,它非常易于使用-
{ path: 'home',
component: HomeComponent,
canActivate: [NgxPermissionsGuard],
data: {
permissions: {
only: 'ADMIN','SuperAdmin'
}
}
},
答案 1 :(得分:0)
我们要遵循的是实现两个Guards AuthGuard(以启用API的身份验证)和CleanGuard(以禁用身份验证)。
现在,在app-routing.module.ts
中指定并配置AuthGuard和CleanGuard。对于我们来说,为特定的一组API启用身份验证,而为某些特定的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' },
];
CleanGuard
@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);
}),
)
}
}