Angular2路由可以使用用户角色参数激活和使用AuthGuard(JWT)

Kam*_*ski 41 javascript authentication roles angular2-routing angular

在这个使用JWT身份验证的exaple项目中,我们将了解如何仅允许经过身份验证的用户访问某些路由:

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 },
];
Run Code Online (Sandbox Code Playgroud)

我想更进一步,并指出用户角色有什么"访问"路由 - 但我不知道如何将参数传递给canActivate AuthGuard(src).所以我想实现这样的目标(例如我有两个角色:Admin和Employee):

  { path: 'home',   component: Home, canActivate: [AuthGuard] },
  { path: 'users',   component: AdminUsers, canActivate: [AuthGuard('Admin')] },
  { path: 'users',   component: Employees, canActivate: [AuthGuard('Employee')] },
Run Code Online (Sandbox Code Playgroud)

我的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;
  }
}
Run Code Online (Sandbox Code Playgroud)

其中JWT.user.role是帮助程序,它读取存储在JWT令牌中的用户角色.有没有办法像上面的想法那样做类似的事情?

小智 82

您可以data使用如下角色设置路径的参数

const appRoutes: Routes = [
{ 
  path: 'account/super-secure', 
  component: SuperSecureComponent, 
  canActivate: [RoleGuard], 
  data: { roles: ['super-admin', 'admin'] } 
}];
Run Code Online (Sandbox Code Playgroud)

再有这canActivateRoleGuard:

canActivate(route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {

    let roles = route.data["roles"] as Array<string>;
    return (roles == null || roles.indexOf("the-logged-user-role") != -1);
}
Run Code Online (Sandbox Code Playgroud)

我认为这可能是另一种方式,而不是为每个角色创造防范.我实际上会采取这种溃败,因为它需要更少的代码并且非常好地处理问题.

  • 当我尝试使用您的解决方案时,我看到以下错误:'ActivatedRouteSnapshot' 类型上不存在“属性‘数据’。”我认为您的解决方案仅适用于旧版本的 angular2 (2认同)

cie*_*nki 6

签名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

  • 这个答案是正确的,在我提问的时候 - 这就是绿色'检查'在这里的原因.但对于新的角度版本,有更好的解决方案(阅读下面的答案) (4认同)