Introduction
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';
@Injectable()
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) {
this.Router.navigate(["/Login"]);
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:
- "": This is the default route, when the application will load, it will default redirect the user to login component.
- "
DashBoard
": This is home component which will get rendered when user will logged in. - "
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
},
{
path: "Dashboard",
component: WebServiceComponent,
canActivate: [RouteGuradService]
},
{
path: "Login",
component: LoginComponent
}
]
AppModule
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';
@NgModule({
declarations: [AppComponent, WebServiceComponent, LoginComponent],
imports: [BrowserModule, FormsModule,
ReactiveFormsModule,
RouterModule.forRoot(RoutingConfig),
LocalStorageModule.withConfig({
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);
this.route.navigateByUrl("/Dashboard");
}
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:
- https://github.com/AkiTechiesEra/CRUD/tree/Development
I hope you like this article. Please vote if you find it valuable.