javascript - Angular2 routing canActivate and AuthGuard (JWT) with user role parameter -
in exaple project jwt authentication se how allow authenticated users route:
import { routerconfig } '@angular/router'; import { home } './home'; import { login } './login'; import { signup } './signup'; import { authguard } './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 }, ];
i make step further , indicate user role have 'access' route - don't know how pass argument canactivate authguard (src). achieve (for instance have 2 roles: admin , employee):
{ path: 'home', component: home, canactivate: [authguard] }, { path: 'users', component: adminusers, canactivate: [authguard('admin')] }, { path: 'users', component: employees, canactivate: [authguard('employee')] },
where authguard (where userrole(= admin or employee or null) passed parameter 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; } }
where jwt.user.role helper read user role stored in jwt token. there way similar above idea?
the signature canactivate
won't allow pass userrole
want to. https://github.com/angular/angular/blob/2.0.0-rc.4/modules/%40angular/router/src/interfaces.ts#l54
it's best separate classes each of user role cases. that's guidance in official docs too: https://angular.io/docs/ts/latest/api/router/index/canactivate-interface.html
Comments
Post a Comment