How to implement router "guards" into your applications to protect routes from direct access.
Router hooks are pieces of code that can be invoked at the different stages of routing lifecycle. In that sense, these hooks are similar to the lifecycle hooks of the routed view models. The difference is that these hooks are shared among multiple routed view models. Therefore, even though the hook signatures are similar to that of the lifecycle hooks, these hooks are supplied with an additional argument that is the view model instance.
If you worked with Aurelia 1, you might know these by their previous name: router pipelines.
Anatomy of a lifecycle hook
Shared lifecycle hook logic can be defined by implementing one of the router lifecycle hooks (canLoad, loading etc.) on a class with the @lifecycleHooks() decorator. This hook will be invoked for each component where this class is available as a dependency.
While the router hooks are indeed independent of the components you are routing to, the functions are basically the same as you would use inside of an ordinary component.
This is the contract for ordinary route lifecycle hooks for components:
The only difference is the addition of the first viewModel parameter. This comes in handy when you need the component instance since the this keyword won't give you access to the component instance like it would in ordinary instance hooks.
Example: Authentication and Authorization
Before starting with the involved details of the shared/global lifecycle hooks, let us first create an example lifecycle hook. To this end, we consider the typical use-case of authorization; that is restricting certain routes to users with certain permission claims.
The example we are going to build in this section is just a toy example. For your production code, perform due diligence to evaluate the potential security threats.
For this example, we will create two lifecycle hooks; one for authentication and another is for authorization. However, before directly dive into that, let us briefly visit, how the routes are configured.
Note that the data property of the route configuration option is used here to define the routes' permission claim. This is used by the auth hooks later to determine whether to allow or disallow the navigation. With that we are now ready to discuss the hooks.
The first hook will check if the current route is protected by a claim and there is a currently logged in user. When there is no logged in user, it performs a redirect to login page. This is shown below.
authentication-hook.ts
import { resolve } from'aurelia';import { IRouteViewModel, NavigationInstruction, Params, RouteNode,} from'@aurelia/router-lite';import { lifecycleHooks } from'@aurelia/runtime-html';import { IAuthenticationService } from'./authentication-service';@lifecycleHooks()exportclassAuthenticationHook {privatereadonly authService:IAuthenticationService=resolve(IAuthenticationService)publiccanLoad( _viewmodel:IRouteViewModel, _params:Params, next:RouteNode ):boolean|NavigationInstruction {if (!next.data?.claim ||this.authService.currentClaims !=null)returntrue;// we add the current url to the return_url query to the login page,// so that login page can redirect to that url after successful login.return`login?return_url=${next.computeAbsolutePath()}`; }}
The second hook will check if the current user has the permission claims to access the route. Where the user does not satisfies the claims requirements the user is redirected to a forbidden page. This is shown below.
Lastly, we need to register these two hooks to the DI container to bring those into action.
main.ts
import { RouterConfiguration } from'@aurelia/router-lite';import { Aurelia, StandardConfiguration } from'@aurelia/runtime-html';import { AuthenticationHook } from'./authentication-hook';import { IAuthenticationService } from'./authentication-service';import { AuthorizationHook } from'./authorization-hook';import { MyApp as component } from'./my-app';(asyncfunction () {consthost=document.querySelector<HTMLElement>('app');constau=newAurelia();au.register( StandardConfiguration, RouterConfiguration, IAuthenticationService,// register the first lifecycle hook AuthenticationHook,// register the second lifecycle hook AuthorizationHook );au.app({ host, component });awaitau.start();})().catch(console.error);
Note that the authentication hook is registered before the authorization hook. This ensures that the authentication hook is invoked before than the authorization hook which is also semantically sensible.
To know more about the order of invocation, please refer the respective section.
And that's the crux of it. You can see this example in action below.
Note that even though in the example we limit the the hooks to only canLoad method, more than one lifecycle methods/hooks can also be leveraged in a shared lifecycle hook (a class decorated by the @lifecycleHooks() decorator).
The globally registered lifecycle hooks are invoked for every components. Thus, it is recommended to use those sparsely. On the other hand, when a hook is registered as a dependency of a particular component, it is invoked only for that one component.
This is shown in the example below, where there are two globally registered hooks, which are invoked for every components.
Note that the globally registered hooks in the example above do nothing significant other than logging the invocations. This is shown below.
You may get a different log depending on your test run. However, it can still be clearly observed that both hook1 and hook2 are invoked for every components. Depending on your use-case, that might not be optimal.
To achieve a granular control on the lifecycle hooks, you can register the hooks as the dependencies for individual routed view models. This ensures that the lifecycle hooks are invoked only for the components where those are registered as dependencies. This shown in the example below where there are three hooks, and one component has two hooks registered as dependencies and another component has only hook registered.
When ChildOne or ChildTwo is loaded or unloaded you can observe that only Hook2 is invoked for ChildTwo, whereas both Hook1 and Hook2 are invoked for ChildOne. Below is an example log from one of such test runs.
You can of course choose to use both kind of registrations. The following example shows that Hook3 is registered globally and therefore is invoked for every components whereas Hook1 is only invoked for ChildOne and Hook2 is only invoked for ChildTwo.
Preemption
When using multiple lifecycle hooks, if any hook returns a non-true value (either a false or a navigation instruction) from canLoad or canUnload, it preempts invocation of the other hooks in the routing pipeline.
This is shown in the following example. The example shows that there are two hooks, namely hook1 and hook2. hook1 return false if the path c1 is navigated with a non-number and non-even number; for example it denies navigation to c1/43 but allows c1/42.
You can see the example in action below.
If you run the example and try clicking the links, you can observe that once hook1 returns false, hook2 is not invoked. One such example log is shown below.
The thumb rule is that the hooks are invoked in the order they are registered. That is if some Hook1 is registered before Hook2 in DI then Hook1 will be invoked before the Hook2. You can see this in the example of globally registered hooks.
That is also true, when registering hooks as one of the dependencies for a custom element. You can see this in the example of hooks as dependencies.
When using both globally registered hooks as well as local dependencies, the global hooks are invoked before the locally registered hooks. You can see this in action in this example.
Lastly, the shared lifecycle hooks are invoked before the instance lifecycle hooks.