我正在基于基于角色的身份验证学习有关Angular 8的简单教程。它具有这个枚举:
export enum Role {
User = 'User',
Admin = 'Admin'
}
[在警卫中,我看不懂本教程代码的一部分(即使已注释):
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authenticationService.currentUserValue;
if (currentUser) {
// check if route is restricted by role
if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1)
The line above what does it mean? There is no user nor admin?
// role not authorised so redirect to home page
this.router.navigate(['/']);
return false;
}
// authorised so return true -->And this one, authorizes the normal user? Or the admin?
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
事实是,canActivate
界面如何区分Admin
和User
?
路线:
const routes: Routes = [
{
path: '',
component: HomeComponent,
canActivate: [AuthGuard]
},
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard],
data: { roles: [Role.Admin] }
},
{
path: 'login',
component: LoginComponent
},
// otherwise redirect to home
{ path: '**', redirectTo: '' }
];
除此以外,我知道还有其他方法,但是这一方法看起来非常简单。我想确认该教程是否建议最好的方法。
谢谢。
基本上route.data.roles && route.data.roles.indexOf(currentUser.role) === -1
检查currentUser
角色是否在路由中定义的角色数组中。如果没有,则转到具有authGuard但未定义任何角色的主页。
由于角色,管理员路由仅对管理员用户可见。