Angular 7 + Spring Boot Login Authentication Example

  • 2019-03-09 03:37 AM
  • 1606

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.

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.

Angular 7 + Spring Boot CRUD Demo

Angular 7 + Spring Boot Application Hello World Example

Angular 7 + Spring Boot Application CRUD Example

Angular 7 + Spring Boot Application Login Example

Angular 7 development

The angular project we will be developing is as follows-
Angular 7 + Spring Boot

Create new authentication service

Angular 7 + Spring Boot

Create a new authentication service where we check if the user name and password is correct then set it in session storage. 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 + Spring Boot

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 + Spring Boot

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 {

  isUserLoggedIn:boolean = false;

  constructor(private loginService:AuthenticationService) { }

  ngOnInit() {
    this.isUserLoggedIn=this.loginService.isUserLoggedIn();
    
  }

}

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 + Spring Boot

Angular 7 + Spring Boot

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 + Spring Boot

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';

const routes: Routes = [
  { path: '', component: EmployeeComponent,canActivate:[AuthGaurdService] },
  { path: 'addemployee', component: AddEmployeeComponent,canActivate:[AuthGaurdService] },
  { path: 'login', component: LoginComponent,canActivate:[AuthGaurdService] },
  { 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

Popular Posts

Full Stack Web Development with Angular and Spring MVC
Building Web App using ASP.NET Web API Angular 7 and SQL Server
Angular 7 Tutorial - Learn Angular 7 by Example
Build a Basic App with Spring Boot and JPA using PostgreSQL
Build a Simple CRUD App with Spring Boot and Vue.js
Build a Basic CRUD App with Laravel and Angular
AngularJS tutorial for beginners with NodeJS, ExpressJS and MongoDB
MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS
Build a CRUD App with Angular and Firebase
Angular Authentication Tutorial
Angular 7 (formerly Angular 2) - The Complete Guide
Angular & NodeJS - The MEAN Stack Guide
Learn and Understand AngularJS
Angular Crash Course for Busy Developers
The Complete Angular Course: Beginner to Advanced
Angular (Full App) with Angular Material, Angularfire & NgRx
The Web Developer Bootcamp

Originally published at https://www.javainuse.com

Suggest