Spring Boot + Angular 12 Login Authentication Program(2023) | CodeUsingJava


































Spring Boot + Angular 12 Login Authentication Program (2023)

In the previous tutorial, we had implemented the the CRUD operations. In this tutorial, we will be implementing the Login Authentication in Angular. The login module will be developed directly using Angular and no changes would be applied in our Spring Boot code.
We will be hardcoded username and password in this application. Only the logged in user will be able to fetch the endpoints.

Angular Project Structure

The updated project structure for the Angular Login is as follows-
angular project str

For creating the functionality of login, it is mandatory that the application is having an authentication service.
authentication service

The purpose of AuthenticationService is to check the the username and the password.
The sessionStorage acts as a storage area which is available for the session.
 
  import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  constructor() { }

  authenticate(username: string, password: string) {
    if (username === "user" && password === "codeusingjava") {
      sessionStorage.setItem('username', username)
      return true;
    } else {
      return false;
    }
  }

  isUserLoggedIn() {
    let user = sessionStorage.getItem('username')
    console.log(!(user === null))
    return !(user === null)
  }

  logOut() {
    sessionStorage.removeItem('username')
  }

}


Now we create a login component, where a form will be made for the purpose of login.
login

The values from here will be sent to the authentication service for authentication. Authenticate method checks the username and password entered by the user and verifies them accordingly.
We have initialised a username with default value named 'user'.
 
  import { Component, OnInit } from '@angular/core';
  import { Router } from '@angular/router';
  import { AuthenticationService } from '../service/authentication.service';
  
  @Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
  })
  export class LoginComponent implements OnInit {
  
  
    username = 'user'
    password = ''
    invalidLogin = false
  
    constructor(private router: Router,
      private loginservice: AuthenticationService) { }
  
    ngOnInit() {
    }
  
    checkLogin() {
      if (this.loginservice.authenticate(this.username, this.password)
      ) {
        this.router.navigate([''])
        this.invalidLogin = false
      } else
        this.invalidLogin = true
    }
  }
  

Inside the login component.html we create a form for the Login purpose.
The username and password fields are present in the form.
 
  <div class="container">
  <div>
    User Name : <input type="text" name="username" [(ngModel)]="username">
    Password : <input type="password" name="password" [(ngModel)]="password">
  </div>
  <button (click)=checkLogin() class="btn btn-success">
    Login
  </button>
</div>

Inside the routing module, we add the LoginComponent.
 
  import { NgModule } from '@angular/core';
  import { RouterModule, Routes } from '@angular/router';
  import { AddCustomerComponent } from './add-customer/add-customer.component';
  import { CustomersComponent } from './customers/customers.component';
  import { LoginComponent } from './login/login.component';
  import { LogoutComponent } from './logout/logout.component';
  import { AuthGuardService } from './service/auth-guard.service';
  
  
  const routes: Routes = [
    { path:'', component: CustomersComponent, canActivate:[AuthGuardService]},
    { path:'addCustomers', component: AddCustomerComponent, canActivate:[AuthGuardService]},
    { path: 'login', component: LoginComponent },
    { path: 'logout', component: LogoutComponent, canActivate:[AuthGuardService] },
  
  ];
  
  @NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
  })
  export class AppRoutingModule { }
  

Logout Component

When the person clicks on logout, the LogoutComponent comes into picture and the username from the sessionStorage is cleared by the AuthenticationService.
 
  import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from '../service/authentication.service';

@Component({
  selector: 'app-logout',
  templateUrl: './logout.component.html',
  styleUrls: ['./logout.component.css']
})
export class LogoutComponent implements OnInit {

  constructor(
    private authentocationService: AuthenticationService,
    private router: Router) {

  }

  ngOnInit() {
    this.authentocationService.logOut();
    this.router.navigate(['login']);
  }

}


Inside the routing path, we add the LogoutComponent:
 
  import { NgModule } from '@angular/core';
  import { RouterModule, Routes } from '@angular/router';
  import { AddCustomerComponent } from './add-customer/add-customer.component';
  import { CustomersComponent } from './customers/customers.component';
  import { LoginComponent } from './login/login.component';
import { LogoutComponent } from './logout/logout.component';
  import { AuthGuardService } from './service/auth-guard.service';
  
  
  const routes: Routes = [
    { path:'', component: CustomersComponent, canActivate:[AuthGuardService]},
    { path:'addCustomers', component: AddCustomerComponent, canActivate:[AuthGuardService]},
    { path: 'login', component: LoginComponent },
    { path: 'logout', component: LogoutComponent, canActivate:[AuthGuardService] },
  ];
  
  @NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
  })
  export class AppRoutingModule { }
  

Adding the Login and Logout inside the Header navigation bar

 
  import { Component, OnInit } from '@angular/core';
  import { AuthenticationService } from '../service/authentication.service';
  
  @Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.css']
  })
  export class HeaderComponent implements OnInit {
  
     ngOnInit(): void {
       
     }
   constructor (public loginService: AuthenticationService ){
       
     }
  
  
  
  }
  
The final header component would be as follows-
The ngIf component is used to check the condition results into true.
 
  <header>
  <nav class ="navbar navbar-expand-md navbar-dark bg-dark">
  <div><a href="https://www.codeusingjava.com" class="navbar-brand">CodeUsingJava</a></div>
  
  <ul class="navbar-nav">
    <li><a *ngIf="loginService.isUserLoggedIn()"  routerLink="/" class="nav-link">View Customers</a></li>
    <li><a  *ngIf="loginService.isUserLoggedIn()" routerLink="/addCustomers" class="nav-link">Add New Customers</a></li>
    <li><a *ngIf="!loginService.isUserLoggedIn()" routerLink="/login" class="nav-link">Login</a></li>
    <li><a *ngIf="loginService.isUserLoggedIn()" routerLink="/logout" class="nav-link">LogOut</a></li>
  
  </ul>
  
  </nav>
  </header>
When the user runs the program, the output is displayed as follows:
We have set the username as user and the password as codeusingjava.
The user is directed to next page only if he enters correct usetname and password.
loginform

addcustomerlogout

Creating the AuthGuardService


We want the functionality that a particular routing needs to be activated only if the user is logged in.
guard
The AuthGuardService implements a method known as canActivate method which will activate the endpoints only after the successful login.
 
  import { Injectable } from '@angular/core';
  import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
  import { AuthenticationService } from './authentication.service';
  
  @Injectable({
    providedIn: 'root'
  })
  export class AuthGuardService {
  
    constructor(private router: Router,
      private authService: AuthenticationService) { }
  
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      if (this.authService.isUserLoggedIn())
        return true;
  
      this.router.navigate(['login']);
      return false;
  
    }
  
  }
  

Under the app-routing.ts file, we add the AuthGuardService
With the help of canActivate method, one can check the condition before the componbent comes into use.
 
  import { NgModule } from '@angular/core';
  import { RouterModule, Routes } from '@angular/router';
  import { AddCustomerComponent } from './add-customer/add-customer.component';
  import { CustomersComponent } from './customers/customers.component';
  import { LoginComponent } from './login/login.component';
  import { LogoutComponent } from './logout/logout.component';
import { AuthGuardService } from './service/auth-guard.service';  
  
  const routes: Routes = [
    { path:'', component: CustomersComponent, canActivate:[AuthGuardService]  },
    { path:'addCustomers', component: AddCustomerComponent,  canActivate:[AuthGuardService] },
    { path: 'login', component: LoginComponent },
    { path: 'logout', component: LogoutComponent, canActivate:[AuthGuardService] },
  
  ];
  
  @NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
  })
  export class AppRoutingModule { }
  

Now, If the user tries to access any other endpoints without login, he is again redirected to the login page. Hence we have successfully implemented login logout functionality in our application.

Downloads-

Angular Code
Spring Boot Code