Using Angular Guards for Route Protection
Discover how to implement route guards in Angular applications to control access and enhance security based on user authentication.
0 likes
42 views
Rule Content
{ "title": "Using Angular Guards for Route Protection", "description": "Discover how to implement route guards in Angular applications to control access and enhance security based on user authentication.", "category": "Angular Cursor Rules", "rules": [ { "name": "Implement Route Guards for Protected Routes", "description": "Ensure that sensitive routes are protected by implementing Angular route guards to control access based on user authentication and authorization.", "examples": [ { "before": "const routes: Routes = [\n { path: 'dashboard', component: DashboardComponent },\n { path: 'admin', component: AdminComponent }\n];", "after": "const routes: Routes = [\n { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },\n { path: 'admin', component: AdminComponent, canActivate: [AuthGuard, AdminGuard] }\n];" } ] }, { "name": "Create an Authentication Guard", "description": "Develop an AuthGuard service that implements the CanActivate interface to check if a user is authenticated before granting access to a route.", "examples": [ { "before": "import { Injectable } from '@angular/core';\nimport { CanActivate, Router } from '@angular/router';\n\n@Injectable({ providedIn: 'root' })\nexport class AuthGuard implements CanActivate {\n constructor(private router: Router) {}\n\n canActivate(): boolean {\n // Check if the user is authenticated\n if (/* user is authenticated */) {\n return true;\n } else {\n this.router.navigate(['/login']);\n return false;\n }\n }\n}" } ] }, { "name": "Implement Role-Based Access Control", "description": "Create additional guards, such as an AdminGuard, to enforce role-based access control by checking user roles before granting access to specific routes.", "examples": [ { "before": "import { Injectable } from '@angular/core';\nimport { CanActivate, Router } from '@angular/router';\n\n@Injectable({ providedIn: 'root' })\nexport class AdminGuard implements CanActivate {\n constructor(private router: Router) {}\n\n canActivate(): boolean {\n // Check if the user has admin role\n if (/* user has admin role */) {\n return true;\n } else {\n this.router.navigate(['/not-authorized']);\n return false;\n }\n }\n}" } ] }, { "name": "Use CanActivateChild for Child Routes", "description": "Apply the CanActivateChild interface to protect child routes within a parent route, ensuring that all nested routes are secured.", "examples": [ { "before": "import { Injectable } from '@angular/core';\nimport { CanActivateChild, Router } from '@angular/router';\n\n@Injectable({ providedIn: 'root' })\nexport class AuthGuard implements CanActivateChild {\n constructor(private router: Router) {}\n\n canActivateChild(): boolean {\n // Check if the user is authenticated\n if (/* user is authenticated */) {\n return true;\n } else {\n this.router.navigate(['/login']);\n return false;\n }\n }\n}" } ] }, { "name": "Implement CanLoad for Lazy-Loaded Modules", "description": "Use the CanLoad interface to prevent the loading of lazy-loaded modules unless the user meets certain criteria, such as being authenticated.", "examples": [ { "before": "import { Injectable } from '@angular/core';\nimport { CanLoad, Route, Router } from '@angular/router';\n\n@Injectable({ providedIn: 'root' })\nexport class AuthGuard implements CanLoad {\n constructor(private router: Router) {}\n\n canLoad(route: Route): boolean {\n // Check if the user is authenticated\n if (/* user is authenticated */) {\n return true;\n } else {\n this.router.navigate(['/login']);\n return false;\n }\n }\n}" } ] }, { "name": "Handle Unauthorized Access Gracefully", "description": "Redirect users to appropriate pages, such as a login or not-authorized page, when they attempt to access routes without proper authentication or authorization.", "examples": [ { "before": "this.router.navigate(['/login']);", "after": "this.router.navigate(['/not-authorized']);" } ] }, { "name": "Test Route Guards Thoroughly", "description": "Write unit tests for all route guards to ensure they function correctly and handle various scenarios, such as authenticated and unauthenticated users, and users with different roles.", "examples": [ { "before": "import { TestBed } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { AuthGuard } from './auth.guard';\n\ndescribe('AuthGuard', () => {\n let guard: AuthGuard;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [RouterTestingModule],\n providers: [AuthGuard]\n });\n guard = TestBed.inject(AuthGuard);\n });\n\n it('should be created', () => {\n expect(guard).toBeTruthy();\n });\n\n // Additional tests for canActivate method\n});" } ] } ] }