Telerik blogs
AngularT2 Dark_1200x303

Today we will look at how we can make sure the routes we create in Angular are accessed by the right people and that we prevent unauthorized access to routes that are private.

Prerequisites

Developers of all levels, from beginners to experts can read this post—it does not matter if you are familiar with beginner concepts in Angular. Here are a few prerequisites you should have so you can follow along through this article’s demonstration:

  • An integrated development environment like VS Code
  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (it usually ships with Node installation)
  • Angular CLI version 8.0 or above
  • A recent version of Angular (this post uses Version 12)

Other nice-to-haves include:

  • Working knowledge of the Angular framework at a beginner level

More Routing Concepts: Guards

So far we have looked at a lot of routing concepts and how Angular makes it really easy to handle all your routing needs. The need we will look at today is special: preventing unauthorized access.

In case you missed them, here are some additional Angular Basics posts about routing:


For all the use cases we have built so far during this series, you can notice that any user who uses the app can navigate anywhere inside the app. This is not bad for a test application, but in a real application with actual users, some routes have to be private and only accessible through authentication.

There are user experience reasons why this is important. Sometimes the users can be unauthorized, or you need to fetch some data for a component they are navigating to or even save pending changes before a user leaves a component.

What You Might Have Been Using

This scenario is not new and so there is a chance you just use a simple if statement to check if users are logged in, and that works for one or two use cases. The issue here is that it becomes a repetition of code as your app grows and more components are added.

Angular provides guards to solve for this. Guards are interfaces already available natively in Angular that let us control access to routes based on conditions we provide in the class of the interface.

What Are Route Guards?

Angular route guards are interfaces provided by Angular which, when implemented, allow us to control the accessibility of a route based on conditions provided in class implementation of that interface.

Here are some types of Angular guards: CanActivate, CanActivateChild, CanLoad, CanDeactivate and Resolve.

What We Are Building: CanActivate

We are building the same Navbar component as in the previous article, Angular Basics: Getting Data From Fragments and Query Params, but creating a guard for one of the components. The first thing to do is to clone this template repository from GitHub so we can focus on creating the guards. Open the unzipped file in your VS Code, and inside the template run this command:

npm install

CanActivate basically answers the question: “Does the user have access to this route?” We use this guard to prevent access to users who are not authorized to access a route.

Create a Simple Auth Service

The first thing to do is to create or connect an authorization service that checks if a user is logged in with methods to log them in or out.

ng generate service auth/auth

Inside it, paste the code block below:

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  isLoggedIn = false;
  constructor() { }
isAuthenticated(){
    return this.isLoggedIn;
  }
}

Here we created a logged checker variable and assigned it a false value and then created a method to return the value. Next thing is to create the guard. You can do that simply with the Angular CLI also.

Creating a Guard

In your terminal, run the command below:

ng generate guard auth/auth

It will ask you what guard you want to create, choose CanActivate and then replace the content with the code block below:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router){};
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot):boolean {
      console.log('CanActivate called');
    let isLoggedIn = this.authService.isAuthenticated();
    if (isLoggedIn){
      return true
    } else {
      this.router.navigate(['/contact']);
    }
  }
  
}

Here we log CanActivate in the console. We also check if the user is authenticated. If they are, we return true so the about component is accessible, and if not we navigate the user to the contact component.

Now that you have set up a guard, the next thing to do is to tell Angular which route you want to guard. For us, that is the about component—we do not want anyone who is not logged in to have access to the about component.

Open your app module file (or whichever place you have routes defined) and replace the content with this one below:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import { AuthService } from './auth/auth.service'
import { AuthGuard } from './auth/auth.guard'
const routes: Routes = [
  {path:'about', component: AboutComponent,canActivate:[AuthGuard]},
  {path:'contact', component: ContactComponent}
];
@NgModule({
  declarations: [
    AppComponent,
    AboutComponent,
    ContactComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [AuthService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here you can see we have updated the CanActivate option in the about path—the route with the guard we created.

Now save all the files and run the app on your dev server. It should look like this in the browser.

User is not authorized, so clicking on About sends them to Contact.

Wrapping Up

This post has introduced you to guards in Angular routing and the various types that exist. We have also seen the way to create the CanActivate guard easily and how to create a service that handles authentication. I hope this was helpful. Happy hacking!


5E9A474B-EBDB-439E-8A4A-3B041B0BEDA6
About the Author

Nwose Lotanna Victor

Nwose Lotanna Victor is a web technology enthusiast who documents his learning process with technical articles and tutorials. He is a freelance frontend web developer based in Lagos, Nigeria. Passionate about inclusion, community-building and movies in Africa, he enjoys learning new things and traveling.

Related Posts

Comments

Comments are disabled in preview mode.