Angular2路由可以使用用户角色参数激活和使用AuthGuard(JWT) [英] Angular2 routing canActivate and AuthGuard (JWT) with user role parameter

查看:205
本文介绍了Angular2路由可以使用用户角色参数激活和使用AuthGuard(JWT)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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路由可以使用用户角色参数激活和使用AuthGuard(JWT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆