Role-Based Access Control (RBAC) is a security model that restricts access to resources based on user roles. In Angular applications, RBAC can be implemented using route guards and directives.
1. Define roles: Create an enumeration or constants representing different user roles, e.g., Admin, User, Guest.
2. Assign roles to users: Store the role information in the user object after successful authentication.
3. Protect routes: Implement route guards like canActivate and canActivateChild to check if the user has the required role before allowing navigation.
4. Example of canActivate guard:
@Injectable()
export class RoleGuard implements CanActivate {
constructor(private authService: AuthService) {}
canActivate(route: ActivatedRouteSnapshot): boolean {
const expectedRole = route.data.expectedRole;
const currentUserRole = this.authService.getCurrentUserRole();
return currentUserRole === expectedRole;
}
}
5. Register guards in routing module:
const routes: Routes = [
{ path: 'admin', component: AdminComponent, canActivate: [RoleGuard], data: { expectedRole: 'Admin' } },
];
6. Protect UI elements: Create custom directives to show/hide elements based on user roles.
7. Example of directive:
@Directive({
selector: '[appHasRole]'
})
export class HasRoleDirective implements OnInit {
@Input() appHasRole: string;
constructor(private el: ElementRef, private authService: AuthService) {}
ngOnInit(): void {
if (!this.authService.userHasRole(this.appHasRole)) {
this.el.nativeElement.style.display = 'none';
}
}
}