Angular Role-Based Routing Access with Angular Guard
Hi everyone,
In this blog post, I would like to show you how to implement role-based access control using Angular 9.
Demo’s scenario;
I have created a simple application that includes Admin, User roles. On the main page the guest will see the showcase to see the web site images.
If the user login as admin, the user can access the /admin route. If the user login as a user, the user can access /user route in the application. If he is a guest, he only can access /home page, neither /admin nor /user route.
I will examine how to implement role-based access between routes.
I will use the Angular Guard to protect routes.
Let’s Begin
- What’a an Angular Guard?
- AuthService
- AuthGuard Implementation
- Routing Module Implementation
What’s an Angular Guard?
The interfaces that inform whether the requested route is allowed are called guards. While performing these operations, the guards look at the return values of the implemented interfaces’ methods.
There are different types of guard methods I listed below.
What are these methods?
CanActivate
Controls whether a route can be activated. Interface that a class can implement to be a guard deciding if a route can be activated. If all guards return true, navigation will continue. If any guard returns false, navigation will be canceled.
CanActivateChild
Interface that a class can implement to be a guard deciding if a child route can be activated. If all guards return true, navigation will continue. If any guard returns false, navigation will be canceled.
CanDeactivate
Interface that a class can implement to be a guard deciding if a route can be deactivated. If all guards return true, navigation will continue. If any guard returns false, navigation will be canceled.
CanLoad
Interface that a class can implement to be a guard deciding if children can be loaded.
Resolve
Interface that classes can implement to be a data provider. A data provider class can be used with the router to resolve data during navigation.
In this blog post, I will use the CanActivate guard to protect the router's link. You can easily implement role-based protection for your router, you could use like CanActivateChild like the same way.
AuthService
I have created an Auth service that provides information about the user’s login status and roles.
I don’t have any integration about jwt token implementation. This is just a simple simulation for login and getting roles.
login() function takes a string argument and store a user login state and role. The value entered as an argument to the role.
logout() function removes the user's information about login from local storage.
isLoggedIn() function inform us whether the user is logged into the system.
getRole() function gives us the user's role from local storage.
AuthService





