在这个带有 JWT 身份验证的 示例项目 中,我们了解如何只允许经过身份验证的用户访问某些路由:
import { RouterConfig } from '@angular/router';
import { Home } from './home';
import { Login } from './login';
import { Signup } from './signup';
import { AuthGuard } from './common/auth.guard';
export const routes: RouterConfig = [
{ path: '', component: Login },
{ path: 'login', component: Login },
{ path: 'signup', component: Signup },
{ path: 'home', component: Home, canActivate: [AuthGuard] },
{ path: '**', component: Login },
];
我想更进一步,并指出哪些用户角色可以“访问”路由 - 但我不知道如何将参数传递给 canActivate AuthGuard (src) 。所以我想实现这样的目标(例如我有两个角色:管理员和员工):
{ path: 'home', component: Home, canActivate: [AuthGuard] },
{ path: 'users', component: AdminUsers, canActivate: [AuthGuard('Admin')] },
{ path: 'users', component: Employees, canActivate: [AuthGuard('Employee')] },
我的 AuthGuard 可能看起来像这样(其中 userRole(= Admin 或 Employee 或 null)将参数传递给 AuthGuard):
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(userRole) {
if (!userRole || JWT.user().role == userRole) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
其中 JWT.user.role 是帮助程序,它读取存储在 JWT 令牌中的用户角色。有没有办法做类似上述想法的事情?
原文由 Kamil Kiełczewski 发布,翻译遵循 CC BY-SA 4.0 许可协议
CanActivate
的签名不允许你像你想的那样传递userRole
。 https://github.com/angular/angular/blob/2.0.0-rc.4/modules/%40angular/router/src/interfaces.ts#L54最好为每个用户角色案例单独上课。这也是官方文档中的指南: https ://angular.io/docs/ts/latest/api/router/index/CanActivate-interface.html