How to Implement Role Based Access Control-in Angular Components

Role-Based Access Control (RBAC) is a crucial security feature for modern web applications, ensuring that users can only access resources and perform actions based on their roles.

In Angular applications, implementing RBAC effectively involves a combination of route guards, service logic, and component-based checks. Here’s a comprehensive guide to help you set up RBAC in your Angular components.

 

Understanding Role-Based Access Control

RBAC is a method of restricting system access to authorized users. The core principle is to assign roles to users and then control their access to resources based on those roles. For instance, an admin might have access to all parts of an application, while a regular user might have limited access.

Setting Up Role-Based Access Control in Angular

1. Define Roles and Permissions

Start by defining the roles and permissions within your Angular application. This can be done by creating an enumeration or constants that represent different user roles.

export enum UserRole {
  Admin = 'ADMIN',
  User = 'USER',
  Guest = 'GUEST',
}

 

2. Create a User Service

A service that manages user roles and permissions is essential. This service should provide methods to check the current user's role and whether they have the required permissions.

import { Injectable } from '@angular/core';
import { UserRole } from './user-role.enum';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private userRole: UserRole = UserRole.Guest; // Default role

  // Method to set user role
  setRole(role: UserRole) {
    this.userRole = role;
  }

  // Method to get user role
  getRole(): UserRole {
    return this.userRole;
  }

  // Method to check if the user has a specific role
  hasRole(role: UserRole): boolean {
    return this.userRole === role;
  }
}

 

3. Implement Route Guards

Angular’s route guards can be used to restrict access to routes based on user roles. You can implement CanActivate or CanLoad guards for this purpose.

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
import { UserRole } from './user-role.enum';

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

  canActivate(): boolean {
    const userRole = this.authService.getRole();

    // Check if user role is allowed
    if (userRole === UserRole.Admin) {
      return true;
    } else {
      this.router.navigate(['/access-denied']); // Redirect to an access denied page
      return false;
    }
  }
}

 

4. Apply Guards to Routes

Integrate the guard into your routing module to restrict access to specific routes.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { RoleGuard } from './role.guard';
import { AdminComponent } from './admin/admin.component';
import { AccessDeniedComponent } from './access-denied/access-denied.component';

const routes: Routes = [
  { path: 'admin', component: AdminComponent, canActivate: [RoleGuard] },
  { path: 'access-denied', component: AccessDeniedComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

 

5. Protect Components

In addition to route guards, you can also conditionally display content within components based on user roles.

import { Component } from '@angular/core';
import { AuthService } from './auth.service';
import { UserRole } from './user-role.enum';

@Component({
  selector: 'app-admin',
  template: `
    <div *ngIf="isAdmin">
      <h1>Welcome Admin!</h1>
      <!-- Admin-specific content goes here -->
    </div>
    <div *ngIf="!isAdmin">
      <p>You do not have permission to view this content.</p>
    </div>
  `
})
export class AdminComponent {
  isAdmin: boolean;

  constructor(private authService: AuthService) {
    this.isAdmin = this.authService.hasRole(UserRole.Admin);
  }
}

Conclusion

Implementing Role-Based Access Control in Angular components involves defining roles, creating a user service to manage roles, applying route guards, and protecting component content based on user roles. By following these steps, you can ensure that your Angular application adheres to secure access practices and provides a tailored user experience.

Related post