1. Create an AuthService to manage user roles:
This service will store the current user's role and provide methods to check access rights.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private userRole: string = 'admin'; // Mock role (In real-world, get it from an API or token)
getUserRole(): string {
return this.userRole;
}
hasRole(role: string): boolean {
return this.userRole === role;
}
}
2. Create a Route Guard:
Generate a route guard that checks if the user has the required role to access the route.
ng generate guard role
Then, implement the guard logic:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class RoleGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean {
const requiredRole = route.data['role']; // Get the required role from route data
if (this.authService.hasRole(requiredRole)) {
return true;
} else {
this.router.navigate(['/unauthorized']); // Redirect if user doesn't have the required role
return false;
}
}
}
3. Define Routes with the Guard:
In the app-routing.module.ts, protect routes using the RoleGuard by specifying required roles in the data field.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AdminComponent } from './admin/admin.component';
import { UserComponent } from './user/user.component';
import { UnauthorizedComponent } from './unauthorized/unauthorized.component';
import { RoleGuard } from './role.guard';
const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
canActivate: [RoleGuard],
data: { role: 'admin' } // Only accessible by users with 'admin' role
},
{
path: 'user',
component: UserComponent,
canActivate: [RoleGuard],
data: { role: 'user' } // Only accessible by users with 'user' role
},
{
path: 'unauthorized',
component: UnauthorizedComponent
},
{
path: '',
redirectTo: '/user',
pathMatch: 'full'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }