Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 role based routing

Tags:

angular5

I've a website with a home page defined in my routing module as:

const appRoutes: Routes = [
{
  path: '',
  component: HomeComponent
}];

Now I would like to display a different home page for admin users (a Dashboard page). Could I change the "component" called based on the user's role?

in pseudo code something like:

const appRoutes: Routes = [
{
  path: '',
  IF UserRole = 'Admin'
     component: DashboardComponent
  ELSE
     component: HomeComponent
}];
like image 580
jcmag Avatar asked Apr 19 '18 13:04

jcmag


People also ask

What is role based access control in angular?

In the system's security, the role-based authorization / role-based access control (RBAC) is a way of restricting and managing machine access to authorized users. RBAC (Role-based access control) confines access to the network based on the employee's role in an organization.

What is ActivatedRouteSnapshot in angular?

ActivatedRouteSnapshotlinkContains the information about a route associated with a component loaded in an outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router state tree.

What is RouteReuseStrategy?

RouteReuseStrategy : In simple sentence it caches the components and prevent it from reload the components again and again. While in angular to navigate from one page to another page, we have an concept called Routing. By using this we can redirect from one page to another.

How many strategies are provided by angular by Locationstrategy?

LocationStrategylink Angular provides two strategies: HashLocationStrategy and PathLocationStrategy .

What is RouterLink?

In Angular, RouterLink is a directive for navigating to a different route declaratively. Router. navigate and Router. navigateByURL are two methods available to the Router class to navigate imperatively in your component classes. Let's explore how to use RouterLink , Router.


1 Answers

Tutorial Link in the @andrea06590 answer has very brief overview for Authentication and Authorization based routing. In a short way , someone can use the following way:

  1. Use canActivate property and pass it a service class which implements CanActivate Interface.
  2. use data object property to pass the role to AuthGuard service.

app.routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
  { path : ''  , redirectTo : '', pathMatch: 'full' , canActivate : [ RedirectGuardService ] },
  { path : 'admin' , component : AdminComponent , canActivate : [AuthGuardService] , data : { role : 'admin'}},
  { path : 'user' , component : UserComponent , canActivate : [AuthGuardService] , data : { role : 'user'}}
  { path : '**' , component : NotFoundComponent }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

auth-guard.service.ts

import { Injectable } from '@angular/core';
import { Router , CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../auth-service/auth-service.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
  constructor(
      private router: Router,
      private authService: AuthService
  ) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean> | Promise<boolean> | boolean {
    const currentUser = this.authService.userVal; // Getting User Value by decoding JWT Token
    const role        = route.data.role; // Getting role value which we passed to data object in router configuration
    if (currentUser) {      
      if(role && role.indexOf(currentUser.role) > -1)
        return true;          
      else 
        return false;          
    }
    return false;
  }
}


redirect-guard.service.ts

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../auth-service/auth-service.service';
import { Observable } from 'rxjs';
import { IUser } from 'client/app/interfaces';

@Injectable({
  providedIn: 'root'
})
export class RedirectGuardService implements CanActivate {
  constructor(
      private router: Router,
      private authService: AuthService
  ) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean> | Promise<boolean> | boolean {
    const user = <IUser>this.authService.userVal;
    if (user && user['user']) {      
      this.router.navigate(['/'+ user['user'].role]);
      return true;      
    }      
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
    return false;
  }
}
like image 80
ImFarhad Avatar answered Oct 20 '22 19:10

ImFarhad