Login and Registration Application using Spring Boot and Angular

Login and Registration Application using Spring Boot and Angular

Overview

Welcome to our step-by-step guide on building a full-stack login and registration web application using Spring Boot for the backend and Angular for the frontend. This guide is designed to be simple, easy to follow, and beginner-friendly. By the end, you’ll have a fully functional application where users can register, log in, and interact with a secure backend.

Login and Registration application using spring boot and angular

If you haven’t already, check out our previous article on Building Robust Login and Registration REST APIs with Spring Boot, JPA, and MySQL to understand the backend setup. In this guide, we’ll focus on the Angular frontend and how to connect it to the Spring Boot backend.

What We’ll Build

  • Backend A Spring Boot application with REST APIs for user registration and login.
  • FrontendAn Angular application with forms for registration and login.
  • Integration Connecting the Angular frontend to the Spring Boot backend.

Tools and Technologies

  • Spring Boot : For building REST APIs.
  • Angular : For building the user interface.
  • MySQL : For storing user data.
  • HttpClient :For making HTTP requests from Angular to Spring Boot.
  • Postman : For testing APIs.

Table of Contents:

  • Recap of the Spring Boot Backend
  • Setting Up the Angular Project
  • Create the Angular Components
  • Create the Registration and Login Forms
  • Set Up Routing in Angular
  • Connect Angular with Spring Boot
  • Enhance the Application

Step 1: Recap of the Spring Boot Backend

Before diving into the Angular frontend, let’s quickly recap the Spring Boot backend setup. If you haven’t set it up yet, follow our previous guide to create the following:

  • User Entity : A User class with fields like id, name, email, and password.
  • UserRepository : A Spring Data JPA repository for database operations.
  • UserService : A service to handle user registration and login logic.
  • UserController : REST endpoints for /addUser and /loginUser.

Once your backend is ready, you can proceed to build the Angular frontend.

Step 2: Setting Up the Angular project

for setup Angular project do the following things –

Install Angular CLI

If you don’t have Angular CLI installed, install it globally using npm:

npm install -g @angular/cli

– Create a New Angular Project

Create a new Angular project using the Angular CLI:

ng new login-registration-app
cd login-registration-app

– Install Required Dependencies

Install Bootstrap for styling and Font Awesome for icons:

npm install bootstrap @fortawesome/fontawesome-free

Add Bootstrap and Font Awesome to the angular.json file:


"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "node_modules/@fortawesome/fontawesome-free/css/all.min.css"
],

"scripts": [
  "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
]

Step 3: Create the Angular Components

Folder Structure

Organize your angular project like this:

        src/
        ├── app/
        │   ├── components/
        │   │   ├── register/
        │   │   │   ├── register.component.ts
        │   │   │   ├── register.component.html
        │   │   │   ├── register.component.css
        │   │   ├── login/
        │   │   │   ├── login.component.ts
        │   │   │   ├── login.component.html
        │   │   │   ├── login.component.css
        │   ├── services/
        │   │   ├── auth.service.ts
        │   ├── app.module.ts
        │   ├── app-routing.module.ts
            

Generate Components

Generate the Register and Login components using Angular CLI:

ng generate component components/register
ng generate component components/login

Create a Service for API Calls

Generate a service to handle HTTP requests:

ng generate service services/auth

Update the auth.service.ts file:


import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  private apiUrl = 'http://localhost:8082';

  constructor(private http: HttpClient) {}

  register(user: any): Observable<any> {
    return this.http.post(`${this.apiUrl}/addUser`, user);
  }

  login(user: any): Observable<any> {
    return this.http.post(`${this.apiUrl}/loginUser`, user);
  }
}

Step 4: Create the Registration and Login Forms

Before updating login and register component make sure you have imported HttpClientModule and ReactiveFormsModule


import { NgModule } from '@angular/core';
import { BrowserModule, provideClientHydration } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { ViewUsersComponent } from './view-users/view-users.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    RegisterComponent,
    ViewUsersComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [
    provideClientHydration()
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Register Component

Update the register.component.ts file:


import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css'],
})
export class RegisterComponent {
  
  register = new FormGroup({
    email: new FormControl(''),
    name: new FormControl(''),
    password: new FormControl('')
  });

  constructor(private authService: AuthService) {}

  onSubmit(): void {
    this.authService.register(this.register.value).subscribe(
      (response) => {
        alert('Registration successful!');
      },
      (error) => {
        alert('Registration failed!');
      }
    );
  }
}

Update the register.component.html file:


<p>Please enter the following information!</p>

<form [formGroup]="register" (ngSubmit)="handleSubmit()">

    <label for="email">Email</label>
    <input type="email" id="email" 
           placeholder="Please enter your email" 
           formControlName="email">

    <br/> <br/> <br/>

    <label for="name">Name</label>
    <input type="text" id="name" 
           placeholder="Please enter your Name" 
           formControlName="name">

    <br/> <br/> <br/>

    <label for="password">Password</label>
    <input type="password" id="password" 
           placeholder="Please enter your password" 
           formControlName="password">

    <br/> <br/> <br/>

    <button type="submit">Register</button>

    <br/> <br/> <br/>

    <a routerLink="/login">Already registered?</a>

</form>

Login Component

Update the login.component.ts file:


import { Component } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
})
export class LoginComponent {
  
  data = new FormGroup({
    email: new FormControl(''),
    password: new FormControl('')
  });

  constructor(private authService: AuthService) {}

  onSubmit(): void {
    this.authService.login(this.data.value).subscribe(
      (response) => {
        alert('Login successful!');
      },
      (error) => {
        alert('Login failed!');
      }
    );
  }
}

Update the login.component.html file:


<p>login works!</p>

<form [formGroup]="data" (ngSubmit)="handleSubmit()">
    <label for="email">User Id</label>
    <input type="email" id="email" 
           placeholder="Please enter your email" formControlName="email">

    <br/> <br/> <br/>
    <label for="password">Password</label>
    <input type="password" id="password" 
           placeholder="Please enter your password" formControlName="password">

    <br/> <br/> <br/>
    <button type="submit">Login</button>

    <br/> <br/> <br/>
    <a routerLink="/register">don't have an Account</a>
</form>

Step 5: Set Up Routing in Angular

Update the app-routing.module.ts file:


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { ViewUsersComponent } from './view-users/view-users.component';

const routes: Routes = [
    {
        path: 'login', component: LoginComponent
    },
    {
        path: 'register', component: RegisterComponent
    },
    {
        path: 'view-users', component: ViewUsersComponent
    }
];

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

Step 6: Connect Angular with Spring Boot

Start the Spring Boot Application

  • Run your Spring Boot application on.
  • http://localhost:8082.

Start the Angular Application

  • Run your Angular application on.
  • http://localhost:4200
ng serve

Test the Application

  • Open your browser and go to http://localhost:4200/register .
  • Fill out the registration form and submit it. You should see a success message.
  • Navigate to http://localhost:4200/login and login with the same credentials.

Step 7: Enhance the Application

Store JWT Tokens

If you’re using JWT for authentication , store the token in localStorage or cookies after login.

Add Protected Routes

Use Angular’s route guards to create protected routes that only logged-in users can access.

Conclusion

Congratulations! You’ve successfully built a full-stack login and registration web application using Spring Boot and Angular. Here’s what you’ve accomplished:

  • Created a secure backend with Spring Boot.
  • Built a user-friendly frontend with Angular.
  • Connected the frontend and backend using Angular’s HttpClient.

This application is a great starting point for building more complex web applications. Feel free to expand it by adding features like password reset, email verification, or user profiles.

Youtube Video –

Github Repository –

https://github.com/amangupta7024/Login-RegisterFlow-Spring-Boot-Angular

Explore our more articles

Create complete web application using spring boot and angular

Welcome to our comprehensive guide on building a full-stack login and registration application using Spring Boot for backend and Angular for the frontend. In this article, we’ll walk you through the entire process step-by-step, using simple and easy-to-understand language. By the end, you’ll have a fully functional application where users can register, log in, and interact with a secure backend.

How to connect Angular with spring boot

Connecting a Angular frontend with a Spring Boot backend is a common requirement for building full-stack web applications. In this section, we’ll explain how to connect Angular with Spring Boot in simple, easy-to-understand steps

1. Setting Up the Angular Project
2. Create the Login and Registration Component in Angular
3. Set Up Routing in Angular
4. Connect Angular to Spring Boot

1 thought on “Login and Registration Application using Spring Boot and Angular”

Leave a Comment