Click here to Skip to main content
14,691,587 members
Articles » Web Development » Web Security » General
Posted 20 Apr 2018


5 bookmarked

Authentication in Angular

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
20 Apr 2018CPOL
Aunthentication of user using canActivate routing in Angular


Authentication plays an important role in making your website secure. In Angular application, apart from service side authentication process. we can also have authentication process at client side using routing and local storage.

Using the Code

Routing Guard Angular Service

I created a service named RouteGuardService and this service implements the CanActivate interface.
CanActivate interface has method canActivate which will be used in the routing config class.

In canActivate method, we check the value of localStorage for "isLoggedIn" key. If the user is logged in, we will return true. If the user is not logged in or say localStorage key "isLoggedIn" is null or empty, then we will return false and redirect the user back to login route or say login page.

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../SharedService/AuthService.Service';
import { LocalStorageService } from 'angular-2-local-storage';

export class RouteGuradService implements CanActivate {
constructor(private authService: AuthService,
private Router: Router,
private LocalStorageService:LocalStorageService) { }

canActivate(route: ActivatedRouteSnapshot, snap: RouterStateSnapshot) {
let isLoggedIn:Boolean=this.LocalStorageService.get("isLoggedIn") as Boolean;
if (!isLoggedIn) {
return false;
return true;

Routing Configuration

We created a separate file for routing configuration and we will use it inside appmodule, i.e., the main module of the application. We have created four routes: 

  1. "": This is the default route, when the application will load, it will default redirect the user to login component.
  2. "DashBoard": This is home component which will get rendered when user will logged in.
  3. "Login": This is created to redirect the use to login component if the user is not authenticated. We can also use the very first "" blank path for the same purpose. But for more understanding, I have created a separate path.
[canActivate]: The canActivate attribute inside routing config is used to do routing authentication. We have passed out service inside the canActivate attribute. If the user is logged in or say if our RouteGuardService returns true, then only the redirect will perform else it will not redirect the user to asked route redirection. 
import { Routes, CanActivate } from "@angular/router";
import { RouteGuradService } from "./RouteGuradService.Service";
import { WebServiceComponent } from "../WebService.Component";
import { LoginComponent } from "../Login.Component";
export const RoutingConfig: Routes = [
path: "",
component: LoginComponent
//Home component route after login
path: "Dashboard",
component: WebServiceComponent,
canActivate: [RouteGuradService]
path: "Login",
component: LoginComponent


In the appModule, we will register our routes:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from "@angular/router";

import { WebServiceComponent } from "./WebService.Component";
import { AppComponent } from './app.component';
import { LoginComponent } from './Login.Component';

import { RoutingConfig } from "./Routing/Routing.Config";
import { RouteGuradService } from "./Routing/RouteGuradService.Service";
import { LocalStorageModule } from 'angular-2-local-storage';

declarations: [AppComponent, WebServiceComponent, LoginComponent],

imports: [BrowserModule, FormsModule,
prefix: 'local-store',
storageType: 'localStorage'

bootstrap: [AppComponent],

providers: [RouteGuradService]
export class AppModule { }

Login Model

You can also directly pass the data as json instead of binding it to model. The choice is upto you but I'm using login model for better coding standard.

export class LoginModel
public username:string;
public password:string;

Login Component Method

Now what we all need to do last is to set the local storage when user enters the correct credentials.

Login(data: LoginModel) {
if (data.username == "akshayk" && data.password == "admin123") {
this.localStorage.set("isLoggedIn", true);
//Redirecting to out home controller if matches the credentials.
else {
this.error = true;
this.localStorage.set("isLoggedIn", false);

Login Page

In login page, when user clicks on login button, the above method will get called. You can use model driven form to create an HTML form. If you don't know how to, just download my application from the below github library.


After implementing this, if the user will try to directly go to our home page using browser URL without login, then it will get redirected back to login page. Sounds Interesting?

You can get the code in my Angular CRUD application. Please download the application from my git library:


I hope you like this article. Please vote if you find it valuable.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior)
India India
I'm Dot net fullstack developer. Having extensive experience in Microsoft technologies, Angular, CSS, bootstrap, Redux, React and Node js.

Comments and Discussions

-- There are no messages in this forum --