Search Tutorials


Angular 7 + Spring Boot Login Authentication Example| JavaInUse

Angular 7 + Spring Boot Login Authentication Example

In previous tutorial we had implemented - Angular 7 + Spring Boot CRUD Example. We had also created a menu with links to pages.
In this tutorial we will be creating a Login and Logout page. We will be using a hard coded user name and password for authenticating a user. Also will be implementing session management so that only a used who is logged in can view the pages. Else he will be directed to the login page. In the next tutorial we will be implementing Basic Authentication using Angular 7 and Spring Boot.
Previously we have seen what is PCF and how to deploy application to PCF..

Angular 7+ Spring Boot - Table of Contents

Angular 7 + Spring Boot Application Hello World Example Angular 7 + Spring Boot Application CRUD Example Angular 7 + Spring Boot Application Login Example Angular 7 + Spring Boot Application Basic Authentication Example Angular 7 + Spring Boot Basic Auth Using HTTPInterceptor Example Angular 7 + Spring Boot JWT Authentication Hello World Example

Video

This tutorial is explained in the below Youtube Video.

We will be modifying the code we developed in theprevious tutorial

Angular 7 development

The angular project we will be developing is as follows-
angular 7 login project

  • Create new authentication service


    angular 7 auth component
    Create a new authentication service where we check if the user name and password is correct then set it in session storage. Using sessionStorage properties we can save key/value pairs in a web browser. The sessionStorage object stores data for only one session . So the data gets deleted if the browser is closed. We will be having the following methods
    • authenticate() Authenticate the username and password
    • isUserLoggedIn() -checks the session storage if user name exists. If it does then return true
    • logout()- This method clears the session storage of user name
    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AuthenticationService {
    
      constructor() { }
    
      authenticate(username, password) {
        if (username === "javainuse" && password === "password") {
          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')
      }
    }
    
  • Create a Login Component


    angular 7 login component
    Using the Login Component we will be taking the username and password from the user and passing it to the authentication service to check if the credentials are valid. It will have the following method-
    checkLogin()- This method checks if the user credentials are correct by calling the previously created AuthenticationService
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 = 'javainuse'
  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
  }

}

Modify the LoginComponent html to add the username and password dialogue boxes-
<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>
Add the login path to the routing module.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EmployeeComponent } from './employee/employee.component';
import { AddEmployeeComponent } from './add-employee/add-employee.component';
import { LoginComponent } from './login/login.component';

const routes: Routes = [
  { path: '', component: EmployeeComponent },
  { path: 'addemployee', component: AddEmployeeComponent },
  { path: 'login', component: LoginComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

  • Create a Logout Component


    angular 7 logout component
    In the logout component we clear the session storage username by calling the authentication service.
    import { Component, OnInit } from '@angular/core';
    import { AuthenticationService } from '../service/authentication.service';
    import { Router } from '@angular/router';
    
    @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']);
      }
    
    }
    
    
    Add the logout path to the routing module-
    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { EmployeeComponent } from './employee/employee.component';
    import { AddEmployeeComponent } from './add-employee/add-employee.component';
    import { LoginComponent } from './login/login.component';
    import { LogoutComponent } from './logout/logout.component';
    
    const routes: Routes = [
      { path: '', component: EmployeeComponent },
      { path: 'addemployee', component: AddEmployeeComponent },
      { path: 'login', component: LoginComponent },
      { path: 'logout', component: LogoutComponent },
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    

  • Modify existing header component to add login , logout menu options

    In the component we check if the user is logged in or not. This will be used to decide if all the menu links should be visible to the user or not.
    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 {
    
      constructor(private loginService:AuthenticationService) { }
    
      ngOnInit() {
        
      }
    
    }
    

    In the header component html we will be adding the login and logout menu. Also we will be showing the menu options to the user only if user is logged in.
     <header>
      <nav class ="navbar navbar-expand-md navbar-dark bg-dark">
      <div><a href="https://www.javainuse.com" class="navbar-brand">JavaInUse</a></div>
      
      <ul class="navbar-nav">
         
        <li><a *ngIf="loginService.isUserLoggedIn()" routerLink="/" class="nav-link">View Employees</a></li>
        <li><a *ngIf="loginService.isUserLoggedIn()" routerLink="/addemployee" class="nav-link">Add New Employee</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>
    	
    Now if we go to localhost:4200/login. Login using the credentials -username ='javainuse' ,password='password'
    angular 7 login page

    angular 7 login success
    But what will happen if the user directly tries to access a page without login. For example if a user directly navigates to localhost:4200 He will be able to view the page. But this should not be the case as the user is not logged in. So we should first check if the user is logged in and only then allow the user to view the page. We achive this using the CanActivate interface.
  • Create the AuthGaurd Service

    We will be creating a new Service named AuthGaurdService. This service will activate a particular route only if the user is logged in.
    ng generate service service/authGaurd
    

    angular 7 authGaurd
    Let the AuthGaurdService implement the CanActivate interface. By overriding the canActivate method we specify that a route should be active only if the user is logged in.
    import { Injectable } from '@angular/core';
    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
    import { AuthenticationService } from './authentication.service';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AuthGaurdService implements CanActivate {
    
      constructor(private router: Router,
        private authService: AuthenticationService) { }
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (this.authService.isUserLoggedIn())
          return true;
    
        this.router.navigate(['login']);
        return false;
    
      }
    
    }
    
    Modify the app.routing.ts to activate route only if the user is logged in using the above AuthGaurdService.
    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { EmployeeComponent } from './employee/employee.component';
    import { AddEmployeeComponent } from './add-employee/add-employee.component';
    import { LoginComponent } from './login/login.component';
    import { LogoutComponent } from './logout/logout.component';
    import { AuthGaurdService } from './service/auth-gaurd.service';
    
    const routes: Routes = [
      { path: '', component: EmployeeComponent,canActivate:[AuthGaurdService] },
      { path: 'addemployee', component: AddEmployeeComponent,canActivate:[AuthGaurdService]},
      { path: 'login', component: LoginComponent },
      { path: 'logout', component: LogoutComponent,canActivate:[AuthGaurdService] },
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    
    Now if the user tries to access a page without logging in, he will be directed to the login page
  • Download Source Code

    Download it -
    GITHUB- Angular 7 Login example code
    Spring Boot Login example code