Angular

    Role Based Authentication Implementation in Angular


    Introduction

    In modern web applications, the crucial aspect is the security of the user's access based on roles, most of the time for data protection and feature control. Angular provides powerful means of implementing Role-Based Authentication, mapping the users only to those sections of the application that they have been authorized to use. In this article, we will look into how to set up role-based authentication using Angular, guards along with a simple authentication service.

    1. Setting Up Authentication and Roles

    A service that manages authentication requires the following:

    • Authentication of users
    • Storing user roles
    • Methods for checking access rights

    Creating a service for authentication

    Let's first create an AuthService that will take care of login, logoff, and all user role management.

    import { Injectable } from '@angular/core';import { Router } from '@angular/router';@Injectable({ providedIn: 'root' })export class AuthService {private user: { username: string; role: string } | null = null;constructor(private router: Router) {}login(username: string, role: string) {this.user = { username, role };localStorage.setItem('user', JSON.stringify(this.user));}logout() {this.user = null;localStorage.removeItem('user');this.router.navigate(['/login']);}getUserRole(): string | null {const userData = localStorage.getItem('user');return userData ? JSON.parse(userData).role : null;}}

    2. Implementing Role-Based Route Guards

    Angular's CanActivate guard helps prevent the unauthorized access. We can create a RoleGuard, which checks for whether the user has the expected role before the navigation to a route.

    Creating a Role Base Guard

    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 expectedRole = route.data['role'];const userRole = this.authService.getUserRole();if (userRole && userRole === expectedRole) {return true;} else {this.router.navigate(['/access-denied']);return false;}}}

    3. Protecting Routes with Role Guards

    To implement role-based access, you will use RoleGuard in the app-routing.module.ts file:

    import { NgModule } from '@angular/core';import { RouterModule, Routes } from '@angular/router';import { RoleGuard } from './role.guard';import { AdminComponent } from './admin/admin.component';import { UserComponent } from './user/user.component';import { LoginComponent } from './login/login.component';import { AccessDeniedComponent } from './access-denied/access-denied.component';const routes: Routes = [{ path: 'admin', component: AdminComponent, canActivate: [RoleGuard], data: { role: 'admin' } },{ path: 'user', component: UserComponent, canActivate: [RoleGuard], data: { role: 'user' } },{ path: 'login', component: LoginComponent },{ path: 'access-denied', component: AccessDeniedComponent },{ path: '**', redirectTo: 'login' }];@NgModule({imports: [RouterModule.forRoot(routes)],exports: [RouterModule]})export class AppRoutingModule {}

    4. Displaying UI Elements Based on Role

    Besides these route protections, we should also show or hide elements dynamically in the UI based on the user role.

    Example

    Conditionally Show Admin Links

    <nav><a routerLink="/user">User Dashboard</a><a *ngIf="authService.getUserRole() === 'admin'" routerLink="/admin">Admin Panel</a></nav>

    Conclusion

    Role-based authentication improves security in Angular and guarantees that sections of an application accessed by users are authorized. We can build secure and scalable Angular applications through authentication services, route guards, and role-based UI conditions.

    Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.

    Contact Us

    Comment

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    Angular

    Related Center Of Excellence