banner



How To Add Authentication Middleware To Angular 6

Angular 8 - Authentication and Authorization


Hallmark is the process matching the visitor of a web application with the pre-defined set of user identity in the organization. In other give-and-take, it is the process of recognizing the user'due south identity. Hallmark is very important process in the organisation with respect to security.

Authorization is the process of giving permission to the user to access certain resource in the system. Only the authenticated user tin be authorised to access a resource.

Let us learn how to do Authentication and Potency in Athwart awarding in this affiliate.

Guards in Routing

In a spider web awarding, a resource is referred by url. Every user in the system will be immune access a set up of urls. For example, an administrator may exist assigned all the url coming under administration department.

Equally we know already, URLs are handled by Routing. Angular routing enables the urls to be guarded and restricted based on programming logic. So, a url may be denied for a normal user and immune for an administrator.

Angular provides a concept called Router Guards which tin exist used to prevent unauthorised access to certain part of the application through routing. Angular provides multiple guards and they are every bit follows:

  • CanActivate − Used to stop the access to a route.

  • CanActivateChild − Used to stop the access to a child road.

  • CanDeactivate − Used to stop ongoing process getting feedback from user. For example, delete procedure can be stop if the user replies in negative.

  • Resolve − Used to pre-fetch the data earlier navigating to the route.

  • CanLoad − Used to load assets.

Working instance

Allow us try to add login functionality to our application and secure it using CanActivate baby-sit.

Open control prompt and become to projection root folder.

cd /go/to/expense-director        

Showtime the application.

ng serve        

Create a new service, AuthService to authenticate the user.

ng generate service auth CREATE src/app/auth.service.spec.ts (323 bytes) CREATE src/app/auth.service.ts (133 bytes)        

Open up AuthService and include beneath code.

import { Injectable } from '@angular/cadre';  import { Observable, of } from 'rxjs'; import { tap, delay } from 'rxjs/operators';  @Injectable({    providedIn: 'root' }) export class AuthService {     isUserLoggedIn: boolean = imitation;     login(userName: cord, countersign: cord): Appreciable            {       panel.log(userName);       console.log(password);       this.isUserLoggedIn = userName == 'admin' && password == 'admin';       localStorage.setItem('isUserLoggedIn', this.isUserLoggedIn ? "true" : "false");      return of(this.isUserLoggedIn).pipe(       delay(grand),       tap(val => {           console.log("Is User Authentication is successful: " + val);        })    );    }     logout(): void {    this.isUserLoggedIn = fake;       localStorage.removeItem('isUserLoggedIn');     }     constructor() { } }                  

Here,

  • We have written two methods, login and logout.

  • The purpose of the login method is to validate the user and if the user successfully validated, it stores the information in localStorage and then returns true.

  • Authentication validation is that the user name and password should be admin.

  • We have not used any backend. Instead, we accept simulated a delay of 1s using Observables.

  • The purpose of the logout method is to invalidate the user and removes the information stored in localStorage.

Create a login component using beneath command −

ng generate component login CREATE src/app/login/login.component.html (twenty bytes) CREATE src/app/login/login.component.spec.ts (621 bytes) CREATE src/app/login/login.component.ts (265 bytes) CREATE src/app/login/login.component.css (0 bytes) UPDATE src/app/app.module.ts (1207 bytes)        

Open LoginComponent and include below code −

import { Component, OnInit } from '@angular/cadre';  import { FormGroup, FormControl } from '@angular/forms'; import { AuthService } from '../auth.service'; import { Router } from '@athwart/router';  @Component({    selector: 'app-login',    templateUrl: './login.component.html',    styleUrls: ['./login.component.css'] }) export course LoginComponent implements OnInit {     userName: cord;    password: string;    formData: FormGroup;     constructor(private authService : AuthService, individual router : Router) { }     ngOnInit() {       this.formData = new FormGroup({          userName: new FormControl("admin"),          password: new FormControl("admin"),       });    }     onClickSubmit(data: any) {       this.userName = data.userName;       this.password = data.password;        console.log("Login folio: " + this.userName);       console.log("Login folio: " + this.password);        this.authService.login(this.userName, this.countersign)          .subscribe( data => {              console.log("Is Login Success: " + data);                    if(information) this.router.navigate(['/expenses']);        });    } }        

Here,

  • Used reactive forms.

  • Imported AuthService and Router and configured information technology in constructor.

  • Created an instance of FormGroup and included 2 case of FormControl, one for user name and some other for countersign.

  • Created a onClickSubmit to validate the user using authService and if successful, navigate to expense list.

Open LoginComponent template and include below template code.

<!-- Page Content --> <div class="container">    <div course="row">       <div class="col-lg-12 text-center" style="padding-top: 20px;">          <div class="container box" style="margin-top: 10px; padding-left: 0px; padding-right: 0px;">             <div grade="row">                <div class="col-12" style="text-align: center;">                                     <form [formGroup]="formData" (ngSubmit)="onClickSubmit(formData.value)"                                            class="form-signin">                                     <h2 class="form-signin-heading">Please sign in</h2>                                     <label for="inputEmail" grade="sr-but">Email address</label>                                     <input type="text" id="username" course="form-control"                                            formControlName="userName" placeholder="Username" required autofocus>                                     <label for="inputPassword" course="sr-just">Password</label>                                     <input type="password" id="inputPassword" class="form-command"                                            formControlName="password" placeholder="Password" required>                                     <button class="btn btn-lg btn-primary btn-block" blazon="submit">Sign in</button>                                     </course>                </div>             </div>          </div>       </div>    </div> </div>        

Hither,

Created a reactive form and designed a login class.

Attached the onClickSubmit method to the form submit action.

Open LoginComponent style and include below CSS Lawmaking.

.grade-signin {    max-width: 330px;     padding: 15px;    margin: 0 auto; }  input {    margin-bottom: 20px; }        

Here, some styles are added to blueprint the login form.

Create a logout component using beneath command −

ng generate component logout CREATE src/app/logout/logout.component.html (21 bytes) CREATE src/app/logout/logout.component.spec.ts (628 bytes) CREATE src/app/logout/logout.component.ts (269 bytes) CREATE src/app/logout/logout.component.css (0 bytes) UPDATE src/app/app.module.ts (1368 bytes)        

Open LogoutComponent and include beneath code.

import { Component, OnInit } from '@angular/core';  import { AuthService } from '../auth.service'; import { Router } from '@angular/router';  @Component({    selector: 'app-logout',    templateUrl: './logout.component.html',    styleUrls: ['./logout.component.css'] }) consign class LogoutComponent implements OnInit {     constructor(private authService : AuthService, private router: Router) { }     ngOnInit() {       this.authService.logout();       this.router.navigate(['/']);    }  }        

Here,

  • Used logout method of AuthService.
  • Once the user is logged out, the page will redirect to home folio (/).

Create a guard using below command −

ng generate guard expense CREATE src/app/expense.guard.spec.ts (364 bytes) CREATE src/app/expense.guard.ts (459 bytes)        

Open ExpenseGuard and include below code −

import { Injectable } from '@athwart/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router'; import { Observable } from 'rxjs';  import { AuthService } from './auth.service';  @Injectable({    providedIn: 'root' }) consign course ExpenseGuard implements CanActivate {     constructor(private authService: AuthService, individual router: Router) {}     canActivate(    next: ActivatedRouteSnapshot,    country: RouterStateSnapshot): boolean | UrlTree {       permit url: string = state.url;            return this.checkLogin(url);       }        checkLogin(url: string): true | UrlTree {          console.log("Url: " + url)          let val: string = localStorage.getItem('isUserLoggedIn');           if(val != null && val == "true"){             if(url == "/login")                this.router.parseUrl('/expenses');             else                 return true;          } else {             return this.router.parseUrl('/login');          }       } }        

Here,

  • checkLogin will check whether the localStorage has the user data and if it is available, then it returns true.
  • If the user is logged in and goes to login page, it will redirect the user to expenses page
  • If the user is not logged in, then the user will exist redirected to login page.

Open up AppRoutingModule (src/app/app-routing.module.ts) and update below code −

import { NgModule } from '@angular/cadre'; import { Routes, RouterModule } from '@athwart/router'; import { ExpenseEntryComponent } from './expense-entry/expense-entry.component'; import { ExpenseEntryListComponent } from './expense-entry-listing/expense-entry-listing.component'; import { LoginComponent } from './login/login.component'; import { LogoutComponent } from './logout/logout.component';  import { ExpenseGuard } from './expense.guard';  const routes: Routes = [    { path: 'login', component: LoginComponent },    { path: 'logout', component: LogoutComponent },    { path: 'expenses', component: ExpenseEntryListComponent, canActivate: [ExpenseGuard]},    { path: 'expenses/detail/:id', component: ExpenseEntryComponent, canActivate: [ExpenseGuard]},    { path: '', redirectTo: 'expenses', pathMatch: 'total' } ];  @NgModule({   imports: [RouterModule.forRoot(routes)],   exports: [RouterModule] }) consign class AppRoutingModule { }        

Here,

  • Imported LoginComponent and LogoutComponent.
  • Imported ExpenseGuard.
  • Created two new routes, login and logout to access LoginComponent and LogoutComponent respectively.
  • Add new pick canActivate for ExpenseEntryComponent and ExpenseEntryListComponent.

Open AppComponent template and add two login and logout link.

<div class="collapse navbar-collapse" id="navbarResponsive">    <ul class="navbar-nav ml-automobile">       <li class="nav-detail active">          <a grade="nav-link" href="#">Home             <span class="sr-only" routerLink="/">(current)</span>           </a>       </li>       <li class="nav-item">          <a class="nav-link" routerLink="/expenses">Study</a>       </li>       <li form="nav-item">          <a form="nav-link" href="#">Add Expense</a>       </li>       <li form="nav-detail">           <a class="nav-link" href="#">Nigh</a>       </li>       <li class="nav-particular">                   <div *ngIf="isUserLoggedIn; else isLogOut">                         <a course="nav-link" routerLink="/logout">Logout</a>                   </div>                    <ng-template #isLogOut>                               <a course="nav-link" routerLink="/login">Login</a>                   </ng-template>       </li>    </ul> </div>        

Open up AppComponent and update below lawmaking −

import { Component } from '@angular/core';  import { AuthService } from './auth.service';  @Component({    selector: 'app-root',    templateUrl: './app.component.html',    styleUrls: ['./app.component.css'] }) export class AppComponent {     title = 'Expense Director';    isUserLoggedIn = false;     constructor(private authService: AuthService) {}     ngOnInit() {       allow storeData = localStorage.getItem("isUserLoggedIn");       console.log("StoreData: " + storeData);        if( storeData != null && storeData == "true")          this.isUserLoggedIn = truthful;       else            this.isUserLoggedIn = simulated;    } }        

Hither, nosotros take added the logic to identify the user status and then that we can show login / logout functionality.

Open AppModule (src/app/app.module.ts) and configure ReactiveFormsModule

import { ReactiveFormsModule } from '@angular/forms';  imports: [     ReactiveFormsModule  ]        

Now, run the application and the application opens the login page.

ReactiveFormsModule

Enter admin and admin as username and countersign so, click submit. The application process the login and redirects the user to expense list page equally shown below −

FormsModule

Finally, your can click logout and leave the awarding.

How To Add Authentication Middleware To Angular 6,

Source: https://www.tutorialspoint.com/angular8/angular8_authentication_and_authorization.htm

Posted by: wardposs1950.blogspot.com

0 Response to "How To Add Authentication Middleware To Angular 6"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel