带有用户角色参数的 Angular2 路由 canActivate 和 AuthGuard (JWT) [英] Angular2 routing canActivate and AuthGuard (JWT) with user role parameter
问题描述
在这个带有 JWT 身份验证的示例项目中我们知道如何只允许经过身份验证的用户访问某些路由:
In this exaple project with JWT authentication we se how to allow only authenticated users to some route:
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).所以我想实现这样的东西(例如我有两个角色:管理员和员工):
I would like make step further and also indicate what user role have 'access' to route - but I don't know how to pass argument to canActivate AuthGuard (src). So I would like to achieve something like this (for instance I have two roles: Admin and Employee):
{ 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):
Where my AuthGuard could look something like this (where userRole(= Admin or Employee or null) is passed parameter to 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 令牌中的用户角色的助手.有没有办法做类似上面的想法?
where JWT.user.role is helper which read user role stored in JWT token. Is there a way to do something similar like above idea?
推荐答案
CanActivate
的签名不允许您按照自己的意愿传递 userRole
.https://github.com/angular/angular/blob/2.0.0-rc.4/modules/%40angular/router/src/interfaces.ts#L54
The signature for CanActivate
won't allow you to pass a userRole
like you want to. 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
It's probably best to do separate classes for each of your user role cases. That's the guidance in the official docs too: https://angular.io/docs/ts/latest/api/router/index/CanActivate-interface.html
这篇关于带有用户角色参数的 Angular2 路由 canActivate 和 AuthGuard (JWT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!