<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Arpan Sarkar</title>
    <description>The latest articles on DEV Community by Arpan Sarkar (@iambetaraybill).</description>
    <link>https://dev.to/iambetaraybill</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1061718%2F69be10e7-aa01-4d23-a59b-0053f6f49461.jpeg</url>
      <title>DEV Community: Arpan Sarkar</title>
      <link>https://dev.to/iambetaraybill</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/iambetaraybill"/>
    <language>en</language>
    <item>
      <title>Permission Based Authorization in Angular (PBAC)</title>
      <dc:creator>Arpan Sarkar</dc:creator>
      <pubDate>Wed, 12 Feb 2025 18:36:11 +0000</pubDate>
      <link>https://dev.to/iambetaraybill/permission-based-authorization-in-angular-pbac-42c7</link>
      <guid>https://dev.to/iambetaraybill/permission-based-authorization-in-angular-pbac-42c7</guid>
      <description>&lt;p&gt;&lt;strong&gt;&lt;em&gt;Authorization&lt;/em&gt;&lt;/strong&gt; is a critical part of any &lt;em&gt;Angular&lt;/em&gt; application, ensuring that users can only access the parts of the application they are permitted to.&lt;br&gt;
In most applications, users have assigned roles.&lt;br&gt;
We can enforce access control in &lt;em&gt;Angular&lt;/em&gt; routes by using route guards.&lt;/p&gt;

&lt;p&gt;In many applications, role based access control (RBAC) alone is not enough. Users may need fine grained permissions beyond just roles. For example:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Admin&lt;/em&gt;&lt;/strong&gt; - Can manage users and edit settings.&lt;br&gt;
&lt;strong&gt;&lt;em&gt;Editor&lt;/em&gt;&lt;/strong&gt; - Can edit articles but not manage users.&lt;br&gt;
&lt;strong&gt;&lt;em&gt;Viewer&lt;/em&gt;&lt;/strong&gt; - Can only view content.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In this article, we’ll see how in &lt;em&gt;Angular&lt;/em&gt; to include &lt;/p&gt;

&lt;blockquote&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Permission Based access control (PBAC)&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;h2&gt;
  
  
  Step 1: Setting Up the &lt;em&gt;Angular&lt;/em&gt; Application
&lt;/h2&gt;

&lt;p&gt;Start by creating a new &lt;em&gt;Angular&lt;/em&gt; app if you don’t have one&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ng new angular-pbac --routing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 2: Create an Auth Service for Dynamic Permissions
&lt;/h2&gt;

&lt;p&gt;This service will store user roles with associated permissions, retrieve them dynamically from an API (mocked for now) and provide authentication authorization methods.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;auth.service.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  private user: { role: string; permissions: string[] } | null = null;

  private rolePermissions: Record&amp;lt;string, string[]&amp;gt; = {
    admin: ['manage-users', 'edit-settings', 'view-dashboard'],
    editor: ['edit-articles', 'view-dashboard'],
    viewer: ['view-dashboard'],
  };

  constructor(private router: Router) {}

  login(role: string): void {
    const permissions = this.rolePermissions[role] || [];
    this.user = { role, permissions };
    localStorage.setItem('userPermissions', JSON.stringify(permissions));
    this.router.navigate(['/dashboard']);
  }

  logout(): void {
    this.user = null;
    localStorage.removeItem('userPermissions');
    this.router.navigate(['/login']);
  }

  getUserPermissions(): string[] {
    return JSON.parse(localStorage.getItem('userPermissions') || '[]');
  }

  hasPermission(permission: string): boolean {
    return this.getUserPermissions().includes(permission);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;For now using mock roles and permissions which normally is retrieved from a backend - &lt;code&gt;rolePermissions&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Here we are doing simple &lt;code&gt;login&lt;/code&gt; method without setting user role or checking if authenticated or not. Just to keep it simple we are avoiding that&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Step 3: Create a Permission Based Route Guard
&lt;/h2&gt;

&lt;p&gt;In &lt;em&gt;Angular&lt;/em&gt;, Route guards help protect routes based on authentication and roles.&lt;br&gt;
Now, we need a route guard to check for both roles and permissions before allowing access.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;permission.guard.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service';

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

  canActivate(route: ActivatedRouteSnapshot): boolean {
    const requiredPermission = route.data['permission'];

    if (!this.authService.hasPermission(requiredPermission)) {
      this.router.navigate(['/unauthorized']);
      return false;
    }

    return true;
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 4: Define Routes with Permission Based Access
&lt;/h2&gt;

&lt;p&gt;Now, we will apply our new permission-based guard to specific routes.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;app.config.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { provideRouter, Route } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { UnauthorizedComponent } from './unauthorized/unauthorized.component';
import { PermissionGuard } from './permission.guard';


const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent },

  // Permission based routes 
  { path: 'edit-settings', component: DashboardComponent, canActivate: [PermissionGuard], data: { permission: 'edit-settings' } },
  { path: 'manage-users', component: DashboardComponent, canActivate: [PermissionGuard], data: { permission: 'manage-users' } },

  { path: 'unauthorized', component: UnauthorizedComponent },
  { path: '', redirectTo: '/login', pathMatch: 'full' },
];

export const appConfig = {
  providers: [provideRouter(routes)],
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 5: Setup Login Component to Handle Dynamic Roles
&lt;/h2&gt;

&lt;p&gt;Now, users can log in as different roles dynamically, and permissions will be applied accordingly.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;login.component.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html'
})
export class LoginComponent {
  constructor(private authService: AuthService) {}

  loginAs(role: string) {
    this.authService.login(role);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;login.component.html&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h2&amp;gt;Login&amp;lt;/h2&amp;gt;
&amp;lt;button (click)="loginAs('admin')"&amp;gt;Login as Admin&amp;lt;/button&amp;gt;
&amp;lt;button (click)="loginAs('editor')"&amp;gt;Login as Editor&amp;lt;/button&amp;gt;
&amp;lt;button (click)="loginAs('viewer')"&amp;gt;Login as Viewer&amp;lt;/button&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 6: Display logged in user Permissions in Dashboard
&lt;/h2&gt;

&lt;p&gt;Now, let’s display permissions dynamically on the dashboard.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;dashboard.component.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
})
export class DashboardComponent {
  permissions: string[];

  constructor(private authService: AuthService) {
    this.permissions = this.authService.getUserPermissions();
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;dashboard.component.html&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h2&amp;gt;Dashboard&amp;lt;/h2&amp;gt;
&amp;lt;p&amp;gt;Hey&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;Your Permissions:&amp;lt;/p&amp;gt;
&amp;lt;ul&amp;gt;
  &amp;lt;li *ngFor="let permission of permissions"&amp;gt;{{ permission }}&amp;lt;/li&amp;gt;
&amp;lt;/ul&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 7: Handling Unauthorized Access
&lt;/h2&gt;

&lt;p&gt;If a user lacks permissions, they will be redirected to an Unauthorized Page.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;unauthorized.component.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component } from '@angular/core';

@Component({
  selector: 'app-unauthorized',
  template: '&amp;lt;h2&amp;gt;Unauthorized Access&amp;lt;/h2&amp;gt;',
})
export class UnauthorizedComponent {}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion: Building a Fortress of Access Control
&lt;/h2&gt;

&lt;p&gt;In this guide, We seen &lt;em&gt;Angular&lt;/em&gt; authorization system by:&lt;br&gt;
✅ Implementing dynamic permissions.&lt;br&gt;
✅ Protecting routes based user permissions.&lt;br&gt;
✅ Automatically handling unauthorized access with redirection.&lt;/p&gt;

&lt;p&gt;Authorization in &lt;em&gt;Angular&lt;/em&gt; is not just about opening and closing doors - it is about building a fortress with layers of security. Roles and Permissions define the broad gates users can pass through, while permissions act as the keys unlocking specific chambers within. By implementing &lt;strong&gt;&lt;em&gt;permission based access control (PBAC)&lt;/em&gt;&lt;/strong&gt;, we create a system that is both scalable and adaptive, which ensures users only access they need.&lt;/p&gt;

&lt;p&gt;As your application grows, this structured approach will become your architectural blueprint, guiding security while maintaining flexibility.&lt;/p&gt;

&lt;p&gt;Did you learn something new today? Let me know in the comments below! 👇&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
