Thursday 5 May 2022

Angular Login with Session Authentication - iFour Technolab

 

Angular Login with Session Authentication

Introduction

In this article, we'll look at how to handle the login process with Session Authentication. We'll verify if the user is logged in or not, and if he is not, then the route will simply be blocked.

Let’s go through the following Angular principles for better understanding.s


Angular Routing module

Manage the user authentication permission for the Angular path.


Angular Auth Guard

This Angular function helps a lot when it comes to handling authentication. This is an interface that instructs the router whether or not to enable navigation to a specific route. We're using the 'canActivate' guard form in this case.


Angular localStorage

In an Angular program, there are three ways to store data on the client-side.

  1. Memory
  2. Session storage
  3. Local Storage.

We're using localStorage in this case, which saves data in the client browser. It can only be used in a modern browser. When the window is closed or reopened while in session storage, the data is retained; however, when the tab is closed, the data will be lost. It's easy to create a new Angular project using a command. Given is the localStorage syntax which simply helps you to save up to 10MB of data in the browser.

Using the below command, create a new Angular project.

npm install bootstrap

Add the following line to the src/styles.css file after installation:

@import '~bootstrap/dist/css/bootstrap.min.css';

Build two components, one for login and one for the dashboard. 

@import '~bootstrap/dist/css/bootstrap.min.css';

Create a service called auth.

Make a new user interface for logging in.

Using the command lines below, create a new guard called auth.

The Angular route guard, which can tell the router whether or not to enable navigation to a requested route, is referred to as Angular guard.

ng g component login

ng g component dashboard

ng g service services/auth //Build a service in the Services folder.

ng g interface interfaces/login //In the interfaces folder, build a new interface.

ng g guard guards/auth //Build a new guard in the Guards folder.

In the Login interfaces, add two properties.

Login.ts


export class ILogin {
userid: string;
password: string;

}

Now navigate to guards/Auth.guard.ts. Import the @angular/router package's 'canActivate' interface.

Auth.guard.ts


import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.isLoggedIn()) {
return true;
}
// navigate to login page as user is not authenticated
this.router.navigate(['/login']);
return false;
}
public isLoggedIn(): boolean {
let status = false;
if (localStorage.getItem('isLoggedIn') == "true") {
status = true;
}
else {
status = false;
}
return status;
}
}

Import the AuthGuard module into the app.module.ts format.

import { AuthGuard } from './guards/auth.guard';

Then, from the @angular/forms package, import ReactiveFormsModule and FormsModule into this file.

Our app.module.ts file should now look like this.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AuthGuard } from './guards/auth.guard';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
DashboardComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule
],
providers: [AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
 

Now edit the app-routing.modue.ts file to include login and dashboard routes. To verify user authentication, add the ‘canActivate' attribute here. It will redirect to the login page if the user is not allowed.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AuthGuard } from './guards/auth.guard';
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent, canActivate : [AuthGuard] }];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

In the app.component.html file, add the HTML code below.

<xmp><div class="container">
<!-- Static navbar --><nav class="navbar navbar-inverse"><div class="container-fluid"><div class="navbar-header"><button aria-controls="navbar" aria-expanded="false" class="navbar-toggle collapsed" data-target="#navbar" data-toggle="collapse" type="button">
<span class="sr-only">Toggle navigation</span></button>
<a class="navbar-brand" href="#">Angular Registration</a></div>
<div class="navbar-collapse collapse" id="navbar"><ul class="nav navbar-nav"><li> </li><li routerlinkactive="active">
<a routerlink="/login">Login</a></li><li> </li><li routerlinkactive="active">
<a routerlink="/dashboard">Dashboard</a></li><li> </li></ul></div>
<!--/.nav-collapse --></div>
<!--/.container-fluid --></nav>
<router-outlet></router-outlet></div>
</xmp>

The path of the URL is stored in routerLink, and routeLinkActive adds the class active to the selected menu. According to the route URL, will determine which View to show.

Import the ILogin interface into the auth.service.ts file.

import { ILogin } from 'src/app/interfaces/login';

Within this service class, add a Logout() method.

import { Injectable } from '@angular/core';
import { ILogin } from '../interfaces/login';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor() { }
logout() :void {
localStorage.setItem('isLoggedIn','false');
localStorage.removeItem('token');
}
}

Now import Router from the @angular/router package into the login.component.ts module. Within this file, import the login interface and the AuthService.

import { Router } from '@angular/router';
import { ILogin } from 'src/app/interfaces/login';
import { AuthService } from '../services/auth.service'

Also, import the @angular/forms package's FormBuilder, FormGroup, Validators.

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

Inside the function Object() { [native code] }, create three instances: router, service, and formBuilder.

constructor(
private formBuilder : FormBuilder,
private router : Router,
private authService : AuthService
) { }

Set default parameters for a new variable modal as the ILogin interface.

model: ILogin = { userid: "admnin", password: "admin@123" }

Make a loginForm variable with the FormGroup sort. The message is a string, and the returnURL is also a string.

loginForm: FormGroup;
message: string;
returnUrl: string;

Build a new formGroup within the ngOnInit() method and apply the necessary validation to both properties.

 

Looking for Trusted AngularJS Development Company ? Your Search ends here.

 
ngOnInit() {
this.loginForm = this.formBuilder.group({
userid: ['', Validators.required],
password: ['', Validators.required]
});
this.returnUrl = '/dashboard';
this.authService.logout();
}

Add a get method to make it easier to access the form.

get f() { return this.loginForm.controls; }

Inside this class, add the Login() method.

login() {
if (this.loginForm.invalid) {
return;
}
else {
if (this.f.userid.value == this.model.userid && this.f.password.value == this.model.password) {
console.log("Login successful");
//this.authService.authLogin(this.model);
localStorage.setItem('isLoggedIn', "true");
localStorage.setItem('token', this.f.userid.value);
this.router.navigate([this.returnUrl]);
}
else {
this.message = "Please check your userid and password";
}
}
}

As a result, login.component.ts would look something like this:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ILogin } from 'src/app/interfaces/login';
import { AuthService } from '../services/auth.service'
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
model: ILogin = { userid: "admnin", password: "admin@123" } 6
loginForm: FormGroup;
message: string;
returnUrl: string;
constructor(
private formBuilder: FormBuilder,
private router: Router,
private authService: AuthService
) { }
ngOnInit() {
this.loginForm = this.formBuilder.group({
userid: ['', Validators.required],
password: ['', Validators.required]
});
this.returnUrl = '/dashboard';
this.authService.logout();
}
// convenience getter for easy access to form fields
get f() { return this.loginForm.controls; }
login() {
// stop here if form is invalid
if (this.loginForm.invalid) {
return;
}
else {
if (this.f.userid.value == this.model.userid && this.f.password.value == this.model.password) {
console.log("Login successful");
//this.authService.authLogin(this.model);
localStorage.setItem('isLoggedIn', "true");
localStorage.setItem('token', this.f.userid.value);
this.router.navigate([this.returnUrl]);
}
else {
this.message = "Please check your userid and password";
}
}
}
}

Login.component.html

<xmp><div class="container"><div class="col-md-6 col-md-offset-3 loginBox"><h3>Log In</h3>
<p>{{message}}</p>
<form><div class="form-group clearfix">
<label class="col-md-3 col-sm-5 col-xs-12" for="userid">Userid</label>
<div class="col-md-9 col-sm-7 col-xs-12">
<input class="form-control" formcontrolname="userid" type="text" /><div><div>Userid is required</div></div></div></div>
<div class="form-group clearfix">
<label class="col-md-3 col-sm-5 col-xs-12" for="password">Password</label>
<div class="col-md-9 col-sm-7 col-xs-12">
<input class="form-control" formcontrolname="password" type="password" /><div><div>Password is required</div></div></div></div>
<div class="col-xs-12 form-group text-right"><button class="btn btn-success" type="submit">Login</button></div></form></div></div>
</xmp>

Dashboard.component.ts

Implement the logout() method inside this.ts format. This page will be inaccessible if the user is not authenticated, and the user will be directed to the login page.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
id: string;
constructor(private router: Router, private authService: AuthService) { }
ngOnInit() {
this.id = localStorage.getItem('token');
//console.log(this.id);
}
logout() {
console.log('logout');
this.authService.logout();
this.router.navigate(['/login']);
}
}

Dashboard.component.html

The logged user's id will be shown within id if the user is registered.

<xmp><div class="container"><div class="col-md-6 col-md-offset-3 loginBox">
Welcome, {{id}}
<a href="javascript:void(0);">Logout</a></div></div>
</xmp>

Conclusion

In this blog, we have learned Angular Login with Session Authentication. We can manage user authentication, route access, and the session variable using this method. If the user is not authenticated, we may use this Angular Guard method to prevent requested navigation.









No comments:

Post a Comment

Unleash the Power of Explainable AI in Banking Software Development

  What exactly is Explainable AI? Explainable AI (XAI) is a subfield of Artificial intelligence (AI) that focuses on developing algorithms a...