Hello guys how are you? Welcome back on my blog Therichpost. Today in this post I am going to share Implementing authorization with roles in Angular 19.
Angular 19 came. If you are new then you must check below two links:
Now guys here is the complete code snippet and please follow carefully:
Implementing authorization with roles in Angular 19 involves several steps, leveraging Angular’s Router Guards, Services, and role-based logic. Below is a detailed guide tailored for Angular 19 with standalone components.
1. Setup Roles and Authentication
Roles are usually provided by your backend service. The user object returned upon login often includes a roles
property. For this example:
{ "username": "john_doe", "roles": ["USER", "ADMIN"] }
2. Create a Mock Auth Service
The AuthService will handle user authentication and store their roles.
// auth.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable({ providedIn: 'root', }) export class AuthService { private currentUserSubject = new BehaviorSubject<any>(null); constructor() {} // Simulate a login login(username: string, password: string): Observable<any> { const mockUser = { username, roles: username === 'admin' ? ['ADMIN'] : ['USER'], }; this.currentUserSubject.next(mockUser); return this.currentUserSubject.asObservable(); } get currentUser(): any { return this.currentUserSubject.value; } logout(): void { this.currentUserSubject.next(null); } hasRole(role: string): boolean { return this.currentUser?.roles.includes(role); } }
3. Implement Role-Based Guard
Use Angular’s Route Guard to check user roles before navigating to routes.
// role.guard.ts import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, } 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 requiredRoles: string[] = route.data['roles']; const hasAccess = requiredRoles.some((role) => this.authService.hasRole(role) ); if (!hasAccess) { this.router.navigate(['/unauthorized']); // Redirect if unauthorized return false; } return true; } }
4. Define Routes with Roles
In Angular 19, routes can be configured directly in standalone components.
// app.routes.ts import { Routes } from '@angular/router'; import { RoleGuard } from './role.guard'; export const routes: Routes = [ { path: 'dashboard', loadComponent: () => import('./dashboard.component').then((m) => m.DashboardComponent), canActivate: [RoleGuard], data: { roles: ['USER', 'ADMIN'] }, // Roles required to access this route }, { path: 'admin', loadComponent: () => import('./admin.component').then((m) => m.AdminComponent), canActivate: [RoleGuard], data: { roles: ['ADMIN'] }, // Only admins can access }, { path: 'unauthorized', loadComponent: () => import('./unauthorized.component').then( (m) => m.UnauthorizedComponent ), }, ];
5. Example Standalone Components
Unauthorized Component
// unauthorized.component.ts import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; @Component({ standalone: true, selector: 'app-unauthorized', template: `<h1>Unauthorized</h1><p>You do not have access to this page.</p>`, imports: [CommonModule], }) export class UnauthorizedComponent {}
Admin Component
// admin.component.ts import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; @Component({ standalone: true, selector: 'app-admin', template: `<h1>Admin Dashboard</h1>`, imports: [CommonModule], }) export class AdminComponent {}
Dashboard Component
// dashboard.component.ts import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; @Component({ standalone: true, selector: 'app-dashboard', template: `<h1>Dashboard</h1>`, imports: [CommonModule], }) export class DashboardComponent {}
6. Bootstrap Application
// main.ts import { bootstrapApplication } from '@angular/platform-browser'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; bootstrapApplication(null, { providers: [provideRouter(routes)], }).catch((err) => console.error(err));
7. Secure Role Checks in Templates
You can conditionally display content based on roles:
// app.component.ts import { Component } from '@angular/core'; import { AuthService } from './auth.service'; import { CommonModule } from '@angular/common'; @Component({ standalone: true, selector: 'app-root', template: ` <button (click)="login('user')">Login as User</button> <button (click)="login('admin')">Login as Admin</button> <button (click)="logout()">Logout</button> <div *ngIf="authService.hasRole('USER')">Welcome, User!</div> <div *ngIf="authService.hasRole('ADMIN')">Welcome, Admin!</div> `, imports: [CommonModule], }) export class AppComponent { constructor(public authService: AuthService) {} login(username: string): void { this.authService.login(username, 'password').subscribe(); } logout(): void { this.authService.logout(); } }
8. Best Practices
- Secure Backend: Always validate roles on the backend for sensitive operations.
- JWT Integration: Use JWT tokens with role claims for production setups.
- Lazy Loading: Lazy-load components for better performance.
Let me know if you need further assistance!
Guys if you will have any kind query then feel free to comment below.
Jassa
Thanks
Recent Comments