Implementing Angular Permissions using Route AuthGuards

In this blog, we’ll see how to use Angular’s route guards to help with authentication.

What are Route Guards?

Angular route guards are interfaces, which checks whether the router allows navigation for the user requested route.

There are different guard types we can use to protect our routes, each of then can be called on particular sequence:

  • CanActivate — Decides whether the requested route can be activated
  • CanActivateChild — Decides whether the children routes of a route can be activated
  • CanDeactivate — Decides whether the requested route can be deactivated
  • CanLoad — Decides if a module can be loaded lazily

Here we see an Example for canActivate guard type,

Eg: When a user is not authenticated and requested for the user dashboard route, we should not permit that route. the user can access that page only if a user is authenticated.

Let’s create a component for the UserDashboard

Add userdashboard route in your application app.router.ts

Here we haven’t given any authguards for route, So everyone can access this page without any permission.

Let’s create a service component using below command

Now, this will add in your application app.module.ts in providers, So that we can use that service in your entire application.

Now, to provide permission for the specific route add this service for that route. At that time when a user hits the route first checks for the authguard based on the return response renders that page.

If it returns true, then page is visible for that user, otherwise user can’t be visible that page.

In your app.router.ts update the router with AuthGuard

--

--

Python, Django, Android and IOS, reactjs, react-native, AWS, Salesforce consulting & development company

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
MicroPyramid

Python, Django, Android and IOS, reactjs, react-native, AWS, Salesforce consulting & development company