How Auth Guard Routes with Angular
Angular comes with a plentiful of features that are extremely helpful for handling authentication. Route guards are one of them that serve this purpose effectively.
So, let’s take a look at what Angular’s route guards are and how they can be used for authentication in your Angular applications.
What are Route Guards?
Angular Router enables navigation from one view to the next as users perform application tasks. At times, we don’t want the user to access all the pages/views without attaining certain permissions or without logging into the application. Angular’s route guards are interfaces that are capable of telling the router whether or not it should allow navigation to a requested route. This decision is made by searching for a true or false return value from a class that implements the given guard interface.
There are five types of guards and each of them is called in a particular sequence. The router modifies the action depending on the guard used. Let’s have a look at the types of guards:
- CanActivate Interface that a class can implement to be a guard deciding if a route can be activated.
- CanDeactivate Interface that a class can implement to be a guard deciding if a route can be deactivated.
- CanActivateChild Interface that a class can implement to be a guard deciding if a child route can be activated.
If all guards return true, navigation will continue. If any guard returns false, navigation will be canceled. If any guard returns a UrlTree, current navigation will be canceled and a new navigation will be initiated to the UrlTree returned from the guard.
Besides the mentioned ones, there are some other useful guards provided by Angular:
- CanLoad
- Resolve
We won’t get into too many details here but you can see the Angular docs ( https://angular.io/api/router ) for more.
Implementation
Step1: Install angular cli
Install Angular CLI by running npm install -g @angular/cli
You can also check the version after installation by running ng –version
Step 2: Create a new angular app by running the below-mentioned command in the terminal :
ng new authGuard — routing
the “ — routing” flag, in the end, will automatically create the file “app-routing.module.ts” file in “/src/app” where we can define all the routes of our application.
You can check out more here: https://angular.io/start
Step 3: Now, let’s switch to the project directory
cd authGuard
Step 4: Run the application
Start the application by running ng serve –open from the command line in the project root folder.
Your browser should automatically open at http://localhost:4200 with the demo Angular app page displayed.
Step 5: Create new components in the application
ng g c login
ng g c dashboard
The above commands will create the component “login” and “dashboard” in the /src/app/ directory and these will be automatically imported in app.module.ts
Step 6: Add “login” and “dashboard” routes in “app-routing.ts” as :
/src/app/app-routing.ts
import { loginComponent } from ‘./components/login/login.component’;
import { homeComponent } from ‘./components/home/home.component’;
const routes: Routes = [
{ path: ‘login’, component: loginComponent },
{ path: ‘’, component: dashboard, pathMatch: ‘full’, canActivate: [LoggedInGuard], },
{ path: ‘*’, component: loginComponent },
{ path: ‘**’, component: loginComponent } //url not found route
];
Step 7 : Import loggedinGuard file app-routing.ts:
import { loginComponent } from ‘./components/login/login.component’;
import { homeComponent } from ‘./components/home/home.component’;
import { LoggedInGuard } from ‘./app.logged-in.guard’;
src/app/app.logged-in.guard :
import { Injectable } from ‘@angular/core’;
import { Router, CanActivate } from ‘@angular/router’;
import { AuthService } from ‘./services/auth-guard.service’;
@Injectable()
export class LoggedInGuard implements CanActivate {
constructor(private user: AuthService,private Router:Router)
{
}
canActivate() {
return this.user.isLoggedIn();
}
}
Step 8: Create a new service that implements the route guard:
You can call it whatever you like, but something like auth-guard. service is generally sufficient.
import { Injectable ,EventEmitter } from ‘@angular/core’;
import {Headers,HttpModule ,Http } from ‘@angular/http’;
import { Routes, RouterModule ,Router ,CanActivate} from ‘@angular/router’;
@Injectable()
export class AuthService {
LoginUser: EventEmitter<any> = new EventEmitter();
private loggedIn = false;
constructor(private http: Http , private router: Router) {
this.loggedIn = !!window.localStorage.getItem(‘auth_token’);
} isLoggedIn() {
if(!window.localStorage.getItem(‘user_id’) || !window.localStorage.getItem(‘auth_token’))
{ this.router.navigate([‘/login’]);
}
return this.loggedIn;
} canActivate() {
if (!this.isLoggedIn()) {
this.router.navigate([‘/login’]);
return false;
}
}
}
The /dashboard route has an extra config value now: canActivate. The AuthGuard that was created above is passed to an array for canActivate which means it will run any time someone tries to access the /dashboard route. If the user is authenticated, they get to the route. If not, they are redirected to the /login route.
My Verdict
If to talk about my general impression of Angular guards, it is rather positive. It was the first time I experimented with a framework’s features that had a completely different approach to solving the issues of modern web and app development. I hope the framework does the same for you and offers you a rich experience.