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

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...