Overview
TheadminGuard is an Angular route guard that implements role-based access control (RBAC) for administrative routes. It verifies that the current user has the ROLE_ADMIN role and redirects non-admin users to the catalog page.
Signature
Type Definition
Implementation
Parameters
Contains information about the route being activated
Contains the router state at a particular moment in time
Return Value
true- User hasROLE_ADMINrole, allow access to the routefalse- User does not have admin role, redirect to/catalogo
Usage
Route Configuration
Apply theadminGuard to admin-only routes:
Combining Guards
For maximum security, combineadminGuard with authGuard:
Guards are executed in the order they appear in the
canActivate array. Always place authGuard before adminGuard to ensure the user is authenticated before checking their role.How It Works
- Role Retrieval: The guard reads the user’s role from
localStorage(src/app/core/guards/admin-guard.ts:8) - Role Validation: Checks if the role equals
'ROLE_ADMIN' - Access Control:
- Admin User: Returns
true, allowing navigation to proceed - Non-Admin User: Redirects to
/catalogoand returnsfalse
- Admin User: Returns
Dependencies
- Router (
src/app/core/guards/admin-guard.ts:5): Angular router for navigation - localStorage: Browser API for retrieving the stored user role
When to Use
UseadminGuard when you need to:
- Restrict access to administrative features and routes
- Implement role-based access control (RBAC)
- Separate user and admin functionality in your application
- Prevent regular users from accessing management interfaces
Security Considerations
Best Practices
- Server-Side Validation: Always validate admin privileges on the backend
- Guard Order: Place
authGuardbeforeadminGuardin thecanActivatearray - Token Validation: Consider implementing token-based role verification instead of relying solely on localStorage
- Fallback Routes: Ensure non-admin users are redirected to appropriate routes
Role System
The guard currently recognizes the following role:ROLE_ADMIN- Full administrative access
Related
- authGuard - Base authentication guard
- publicGuard - Guard for public/unauthenticated routes
- TokenStorageService - Token and user data management