Skip to main content

Angular Authentication: Using Route Guards

Angular comes with a number of baked-in features which are tremendously helpful for handling authentication. I think my favorite is probably its HttpInterceptor interface, but right next to it would be route guards. Let’s take a look at what Angular’s route guards are and how to use them to help with authentication in your Angular apps.
Follow me on Twitter for more content like this

What are Route Guards?

Angular’s route guards are interfaces which can tell the router whether or not it should allow navigation to a requested route. They make this decision by looking for a true or false return value from a class which implements the given guard interface.
There are five different types of guards and each of them is called in a particular sequence. The router’s behavior is modified differently depending on which guard is used. The guards are:
  • CanActivate
  • CanActivateChild
  • CanDeactivate
  • CanLoad
  • Resolve
We won’t get too much into the details of each guard here but you can see the Angular docs for more.
Quick note: I’ve just released a book calledSecuring Angular Applications. It will teach you everything you need to know to properly add authentication and authorization to you Angular app. You’ll also learn how to mitigate common security threats. Check it out if you’re interested :)

Routing Decisions Based on Token Expiration

If you’re using JSON Web Tokens (JWT) to secure your Angular app (and I recommend that you do), one way to make a decision about whether or not a route should be accessed is to check the token’s expiration time. It’s likely that you’re using the JWT to let your users access protected resources on your backend. If this is the case, the token won’t be useful if it is expired, so this is a good indication that the user should be considered “not authenticated”.
Create a method in your authentication service which checks whether or not the user is authenticated. Again, for the purposes of stateless authentication with JWT, that is simply a matter of whether the token is expired. The JwtHelperService class from angular2-jwt can be used for this.
Use angular-jwt in your AuthService
Note: This example assumes that you are storing the user’s JWT in local storage.
Create a new service which implements the route guard. You can call it whatever you like, but something like auth-guard.service is generally sufficient.
The service injects AuthService and Router and has a single method called canActivate. This method is necessary to properly implement the CanActivateinterface.
The canActivate method returns a boolean indicating whether or not navigation to a route should be allowed. If the user isn’t authenticated, they are re-routed to some other place, in this case a route called /login.
Now the guard can be applied to any routes you wish to protect.
The /profile route has an extra config value now: canActivate. The AuthGuardthat was created above is passed to an array for canActivate which means it will be run any time someone tries to access the /profile route. If the user is authenticated, they get to the route. If not, they are redirected to the /login route.
Note: The canActivate guard still allows the component for a given route to be activated (but not navigated to). If we wanted to prevent activation altogether, we could use the canLoad guard.

Checking for a User’s Role

The above example works well for scenarios that are fairly straight forward. If a user is authenticated, let them pass. There are many cases, however, where we’ll want to be a bit more fine-grained with our routing decisions.
For example, we may wish to only permit access to a route for users that have a certain role attached to their account. To handle these cases we can modify the guard to look for a certain role in the payload of the user’s JWT.
Install jwt-decode so we can read the JWT payload.
Since there will be times that we want to use both the catch-all AuthGuard and a more fine-grained role-based guard, let’s create a new service so we can handle both cases.
Create a new guard service called RoleGuardService.
In this guard we’re using ActivatedRouteSnapshot to give us access to the data property for a given route. This data property is useful because we can pass an object with some custom properties to it from our route configuration. We can then pick up that custom data in the guard to help with making routing decisions.
In this case we’re looking for a role that we expect the user to have if they are to be allowed access to the route. Next we are decoding the token to grab its payload. If the user isn’t authenticated or if they don’t have the role we expect them to have in their token payload, we cancel navigation and have them log in. Otherwise, they are free to proceed.
We can now use this RoleGuardService for any of our routes. We might, for example, want to protect an /admin route.
For the /admin route, we’re still using canActivate to control navigation, but this time we’re passing an object on the dataproperty which has that expectedRole key that we’ve already seen in the RoleGuardService.
Note: This scenario assumes that you are using a custom role claim in your JWT.

Isn’t this Easily Hackable?

If you’re like most developers, you’re probably looking at this and thinking that the user could very easily hack their way to a protected route. After all, any knowledgeable user could find their JWT in local storage, head over to jwt.io, plug the token in, and change its payload. For example, they could change the exp in an attempt to extend the token’s lifetime, or they could give themselves a different role.
This is all true–a user could do this and then get past the guards. The key point to remember, however, is that any change the user makes to their token payload will invalidate the signature. JSON Web Token signatures are calculated by including the payload, so any modifications to it will throw the whole thing off. This is good news because it means the user won’t be able to access your protected resources with it.
Any sensitive data that you don’t want unauthorized access to should be kept behind your server. If the user does manage to get to a route they’re not supposed to, it doesn’t matter a whole lot anyway because they won’t be able to see any data that the route normally provides.

But I Want to Lock Routes Down Completely

In some cases, there’s still a strong desire to lock down client-side routes completely. While it’s not possible to have 100% protection of anything on the client side, Angular provides some interesting possibilities through async routing. We’ll have a look at how we can use async routing to our advantage is a future post.

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...