Angular 7 + Spring Boot Login Authentication Example
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.Angular 7 development
The angular project we will be developing is as follows-
-
Create new authentication service
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
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