Dylan  Iqbal

Dylan Iqbal

1560837722

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.

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-

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. 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

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

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’

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

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

#angular #java #spring-boot

What is GEEK

Buddha Community

Angular 7 + Spring Boot Login Authentication Example
Were  Joyce

Were Joyce

1622798007

Angular 12 + Spring Boot: JWT Authentication example | Spring Security

In this tutorial, I will show you how to build a full stack Angular 12 + Spring Boot JWT Authentication example. The back-end server uses Spring Boot with Spring Security for JWT Authentication & Role based Authorization, Spring Data JPA for interacting with database. The front-end will be built using Angular 12 with HttpInterceptor & Form validation.

Related Posts:

– Angular 12 + Spring Boot: CRUD example

– Angular 12 + Spring Boot: File upload example

– Spring Boot, MongoDB: JWT Authentication with Spring Security

Contents [hide]

#angular #full stack #spring #angular #angular 12 #authentication #authorization #jwt #login #registration #security #spring boot #spring security #token based authentication

I am Developer

1609902140

Angular 11 Facebook Social Login Example

Angular 9/10/11 social login with facebook using angularx-social-login library example. In this tutorial, i would love to show you how to integrate facebook social login in angular 11 app.

And you will learn how to add facebook social login button with angular reactive login form.

Angular 11 Social Login with Facebook Tutorial

  • Step 1 - Create New Angular App
  • Step 2 - Install Social Login Library
  • Step 3 - Add Code on App.Module.ts File
  • Step 4 - Add Code on View File
  • Step 5 - Add Code On App.Component ts File
  • Step 6 - Start the Angular Facebook Login App

https://www.tutsmake.com/angular-11-facebook-login-tutorial-example/

#angular 11 facebook login #angular 11 social-login example #login with facebook button angular 8/9/10/11 #angular 10/11 login with facebook #angular 10 social facebook login #angular social login facebook

I am Developer

1610191977

Angular 11 Google Social Login Example

Angular 9/10/11 social login with google using angularx-social-login library example. In this tutorial, i will show you step by step on how to implement google social login in angular 11 app.

And also, this tutorial will show you How to login into Angular 10/11 application with google using angularx-social-login library in angular 11 app.

Google Login Integration In Angular 11 App

  • Step 1 - Create New Angular App
  • Step 2 - Install Social Login Library
  • Step 3 - Add Code on App.Module.ts File
  • Step 4 - Add Code on View File
  • Step 5 - Add Code On App.Component ts File
  • Step 6 - Start the Angular Google Login App

https://www.tutsmake.com/angular-11-google-social-login-example/

#angular 11 google login #angular 11 social-login example #login with google button angular 8/9/10/11 #angular 10/11 login with google #angular 10 social google login #angular social login google

I am Developer

1610191977

Angular 11 Google Social Login Example Tutorial

Angular 9/10/11 social login with google using angularx-social-login library example. In this tutorial, i will show you step by step on how to implement google social login in angular 11 app.

And also, this tutorial will show you How to login into Angular 10/11 application with google using angularx-social-login library in angular 11 app.

Google Login Integration In Angular 11 App

  • Step 1 - Create New Angular App
  • Step 2 - Install Social Login Library
  • Step 3 - Add Code on App.Module.ts File
  • Step 4 - Add Code on View File
  • Step 5 - Add Code On App.Component ts File
  • Step 6 - Start the Angular Google Login App

https://www.tutsmake.com/angular-11-google-social-login-example/

#angular 11 google login #angular 11 social-login example #login with google button angular 8/9/10/11 #angular 10/11 login with google #angular 10 social google login #angular social login google

Sigrid  Farrell

Sigrid Farrell

1622597127

Angular 12 + Spring Boot: CRUD example

In this tutorial, we will learn how to build a full stack Spring Boot + Angular 12 example with a CRUD App. The back-end server uses Spring Boot with Spring Web MVC for REST Controller and Spring Data JPA for interacting with embedded database (H2 database). Front-end side is made with Angular 12, HttpClient, Router and Bootstrap 4.

Run both Project on same server/port:

How to Integrate Angular with Spring Boot Rest API

Contents [hide]

#angular #full stack #spring #angular #angular 12 #crud #h2 database #mysql #postgresql #rest api #spring boot #spring data jpa