If you ever have to implement user authentication (log in or sign in) or user authorization (is the current user allowed to see that screen?), this article is for you!
We’ll take a look at how to use Angular Guards as a way to:
- Check if the current user is logged in
- Redirect the user to a login/sign-in screen if needed
- Check if the user is allowed to navigate to a specific screen/component, and decide what to do from there
Enter Route Guards
A route guard is an Angular service that implements a specific method (usually canActivate) that will return one of the following values every time route navigation happens:
- If it returns
true
, the navigation process continues. - If it returns
false
, the navigation process stops, and nothing happens. - If it returns a
UrlTree
, the current navigation cancels, and new navigation starts to theUrlTree
returned (a UrlTree is a path that we want to redirect to)
Let’s take a look at an example. The following route guard uses a LoginService to check if the user is logged in. If that is the case, the user can navigate to their intended destination. Otherwise, they’re redirected to /login:
@Injectable() export class AuthGuard implements CanActivate { constructor(public service: LoginService, public router: Router{ } canActivate(): boolean | UrlTree { return this.service.isUserLoggedIn() || this.router.parseUrl('login'); } }
You can see that the canActivate method returns true if the user is logged in and returns a UrlTree if the user isn’t. Again, a UrlTree is just a redirect to a different place, in our case, a LoginComponent.
For the above guard to work correctly, we have to tell Angular when this guard is supposed to come into play and which components it is supposed to “protect”. This happens in our routing config, usually app.routing.ts:
const appRoutes: Routes = [ { path: '', component: StoreViewComponent },{ path: 'checkout', component: CheckoutViewComponent, canActivate: [AuthGuard] // Our guard protects /checkout },{ path: 'login', component: LoginComponent } ];
The above configuration shows that our guard only protects one route in our application, /checkout. The other routes are “public”, and the guard’s canActivate method will only be called when a user tries to navigate to /checkout, and not /login, for instance.
What about authorization and multiple different roles?
The router config can have multiple guards applied to one single route. As a matter of fact, the canActivate property takes an array of guards as a parameter:
{ path: 'admin', component: AdminViewComponent, canActivate: [AuthGuard, AdminRoleGuard] },
As a result, we can define several guards for several different purposes, as illustrated in the above example:
- An AuthGuard that will check if the user is logged in and redirect to a login screen if that’s not the case
- An AdminRoleGuard will check if the current user is an administrator and redirect to an error screen if that’s not the case.
We can have as many guards as we want, so it is possible to fine-tune any rule/role we want to check before allowing navigation.
Other guard methods: CanActivateChild, CanLoad, CanDeactivate
Let’s start with CanActivateChild, which behaves exactly like CanActivate but for child routes. The critical difference is that it runs before any child route is activated:
{ path: 'admin', component: AdminComponent, canActivate: [AuthGuard], children: [ { path: '' canActivateChild: [AuthGuard], children: [... ] } ] }
Then we have CanDeactivate, which prevents navigating away from a route. So, for instance, when we have a form that has to be filled out before the user can do anything else, we can use CanDeactivate to make sure that the user does not navigate away from the form before submitting it.
Finally, CanLoad is for routes that use lazy-loading and can be used to prevent loading the code of such routes if we don’t want the user to access those routes in the first place:
{ path: 'team/:id', component: TeamComponent, loadChildren: () => import('./team').then(mod => mod.TeamModule), canLoad: [CanLoadTeamSection] }
My name is Alain Chautard. I am a Google Developer Expert in Angular, as well as a consultant and trainer at Angular Training where I help web development teams learn and become comfortable with Angular.
If you need any help with web development, feel free to get in touch!
If you enjoyed this article, please clap for it or share it. Your help is always appreciated. You can also subscribe to Medium here.
- 登录 发表评论