I am trying to restrict the user access to specific routes depending on the user role. I've created a new role guard to do this but am still able to access the restricted routes.Thanks in advance for your help
Here is my guard:
export class RoleGuard implements CanActivate {
role: string;
constructor(private router: Router) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
this.getRole().subscribe(data => {
this.role = data;
});
const userRole = JSON.parse(localStorage.getItem('user_role'));
if (userRole === 'admin'&& this.role === 'ADMIN') {
// role not authorised so redirect to home page
this.router.navigate(['']);
return false;
}
else {
return true;
}
}
getRole(): Observable<any> {
return this.router.events.pipe(map(data => {
if (data instanceof ChildActivationStart) {
return data.snapshot.data.roles;
}
}));
}
}
When I tried logging the role in the guard, I could see the value coming as undefined after the initial admin value which means canActivate is being called multiple times but the getRole method is called only once. Here is my routing module:
const routes: Routes = [{
path: '',
pathMatch: 'prefix',
component: AppComponent,
canActivate: [AuthGuard],
children: [
{
path: 'admin',
canActivate: [RoleGuard],
data: {
title: 'Admin Support',
roles: 'ADMIN'
},
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
},
{
path: 'user',
loadChildren: () => import('./user/user.module').then(m => m.UserModule)
}
],
}