An application will have N number of routes, but it is possible that many of them have access restrictions only for administrators or certain user roles.
In these cases, the Guards come to help us to give security to our routes.
How to secure Routes
With the help of the Angular CLI, you can create your first guard with the command ng generate guard <guard-name> or in its short form ng g g <guard-name>.
1. Creating the first guard
When using this command, it will ask us a question about which interface you want it to implement by default:
Each option has different functionality for each Guard type. Choose the first option called CanActivate.
When you auto-generate the code, you will see your first Guard looking like this.
A Guard can return a boolean, a promise with a boolean or an observable, also with a boolean. Depending on the logic you have to apply for the case, either synchronous or asynchronous.
2. Importing the guard
Now import the new Guard the routing of your application.
Add canActivate: [ AdminGuard ] to the routes you want to secure.
This way, you can implement the logic you need for each Guard. In this case, allow access to the CMS module for admin users only.
Contribution created by: Kevin Fiorentino.
Contributions 14
Questions 3
Sort by:
Want to see more contributions, questions and answers from the community?
Bueno ya sabemos que los profesores están despegados de los comentarios de sus alumnos, porque no contestan nada, ni a preguntas ni a nada, que lástima, con lo buena que es esta plataforma …
Si están trabajando con el código anterior y no lo han descargado del repositorio del profesor, como yo eh hecho. Probablemente tengan problemas con el Login. El problema es que como cambiaron de API, el usuario que por default pusieron en el código anterior no existe. Para esto solo tienen que crear un nuevo usuario con el siguiente endpoint:
Want to see more contributions, questions and answers from the community?