My RoleGuard 看起来像这样:
import { CanLoad, Route } from "@angular/router";
import { AuthenticationService } from "../_services";
import { Injectable } from "@angular/core";
@Injectable({ providedIn: 'root' })
export class RoleGuard implements CanLoad {
constructor(private authService: AuthenticationService) { }
canLoad(route: Route) {
let authorities = route.data.roles;
if (this.authService.hasAnyRole(authorities)) {
return true;
}
return false;
}
}
以及我在身份验证服务中的方法:
hasAnyRole(roles: string[]): boolean {
for (let i = 0; i <= roles.length; i++) {
if (this.hasRole(roles[i])) {
return true;
}
}
return false;
}
hasRole(role: string): boolean {
let authorities = this.getAuthority();
return authorities.findIndex(a => a === role) > -1;
}
app.routing.ts :
const appRoutes: Routes = [
{
path: 'login',
component: LoginComponent,
canActivate: [NoAuthGuard]
},
{
path: 'password',
component: PasswordComponent,
canActivate: [NoAuthGuard]
},
{
path: 'change-password',
component: ChangePasswordComponent,
canActivate: [ChangePasswordGuard]
},
{
path: 'reset-password',
component: ResetPasswordComponent,
canActivate: [ResetPasswordGuard],
resolve: {
recoverPassword: ResetPasswordGuard
}
},
{
path: '',
component: HomeComponent,
canActivate: [AuthGuard],
children: [
{
path: 'users',
loadChildren: '../app/users/users.module#UsersModule',
canLoad: [RoleGuard],
data: { roles: ['AK.W.1'] }
},
{
path: 'products',
loadChildren: '../app/products/products.module#ProductsModule',
canLoad: [RoleGuard],
data: { roles: ['AK.W.1', 'AK.W.2'] }
},
{
path: 'codes',
loadChildren: '../app/codes/codes.module#CodesModule',
canLoad: [RoleGuard],
data: { roles: ['AK.W.1', 'AK.W.2'] }
},
{
path: 'reports',
loadChildren: '../app/reports/reports.module#ReportsModule',
canLoad: [RoleGuard],
data: { roles: ['AK.W.1','AK.W.2','AK.W.3'] }
}
]
},
{ path: '**', redirectTo: '' }
];
组件的用户授权角色在路径的数据中提供,并在授权服务中签入。方法从令牌中获取用户的角色,并将其与路径数据中提供的角色进行比较。 问题是防护无法正常工作。有时,它允许未经授权的用户在提供应用程序时首次登录后让本地主机上的安全组件进入。你能告诉我我的警卫有什么问题吗?
问题可能出在CanLoad
上。CanLoad
Gaurd 保护要装载的module
,但一旦装载module
CanLoad
守卫就什么都不做。
例如,假设一个用户登录了应用程序,然后导航到某个模块。之后,他单击注销。现在,如果用户想要,他将能够导航到同一模块,因为它已经加载了。
因此,如果要保护您的应用程序,最好是使用CanActivate
.
将
CanActivate
添加到您的角色葫芦中
import { CanLoad, CanActivate, Route,Router,
ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from "../_services";
import { Injectable } from "@angular/core";
@Injectable({ providedIn: 'root' })
export class RoleGuard implements CanLoad, CanActivate {
constructor(private authService: AuthenticationService,private router: Router) { }
canLoad(route: Route) {
let authorities = route.data.roles;
if (this.authService.hasAnyRole(authorities)) {
return true;
}
return false;
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let authorities = route.data.roles;
if (this.authService.hasAnyRole(authorities)) {
return true;
}
return false;
}
}