User Authentication Service Using Spring Boot

In this article, we are going to create a user authentication Service for our full-stack project, for this authentication service we use spring boot and MySQL

Create a Spring Boot Project

Let’s start with creating spring boot project . Go to https://start.spring.io/ and create a spring boot maven project with data JPA, mqsql, lambok and spring web dependencies. and generate the project and open in your preffered IDE.(I’m going to use intellij idea).

spring boot project

after generating the spring boot project extract it and open it in IDE. The initial project structure is as follows

spring boot project

let’s start coding . First we are going to create model class. Create a package model and create a class model

Model Class

In our model class we are going to create fields for id, name, emailId,password and user type. In our project there is two type of users 1. normal user 2. provider, who is service provider. for storing user type we created a Enum class.

userType.java

package com.gangforcode.authentication.model;

public enum userType {
provider,user;
}

User.java

In the model class ‘User.java’ we make id as primary key and it will be auto generated and ’emailId’ should be unique for every one.

package com.gangforcode.authentication.model;
import jakarta.persistence.*;
import lombok.Data;

@Entity
@Table(name = "authentication")
@Data
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@Column(unique = true)
private String emailId;
private userType type;
private String password;
}

let’s create repository for database related operation

Spring Boot MySQL Repository

We are going to create repository by extending JpaRepository<>. We already added dependencies for JPA and MySQL in our project. By extending JpaRepository we don’t need to write queries for database it will automatically perform our most of the tasks.

let’s create a package repository and create a package name repo and inside that create a interface named repository by extending JpaRepository. And write a custom method ‘findByEmailIdAndPassword’. we will use this method during login to verify email Id and password.

Repository.java

package com.gangforcode.authentication.reoo;

import com.gangforcode.authentication.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface Repository extends JpaRepository<User,Integer> {
User findByEmailIdAndPassword(String emailId,String password);
}

Now we are going to create Controller and in the controller we directly auto wire repository. If you want you can create a service layer .

MySQL Spring Boot Configuration

for connecting with database we need to add some properties in ‘application.yml’ file like database url, username , password and some other properties. Add following properties in your ‘application.yml’ file for mysql configuration

spring.datasource.url=jdbc:mysql://localhost:3306/gfcAuth?createDatabaseIfNotExist=true
spring.datasource.username=username
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Change username and password according to your database.

final ‘application.properties’ file for this microservice

application.properties

server.port=8000
spring.application.name=authentication
spring.datasource.url=jdbc:mysql://localhost:3306/gfcAuth?createDatabaseIfNotExist=true
spring.datasource.username=username
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

When you run the service first time it will automatically create database and table if database and table does not exists.

spring boot mysql

Controller

Let’s create controller, In this controller we are going to implement logic for different end points like registrations, login , forget password and etc.

create a ‘AuthController’ class inside controller package and inside this class auto wire repository and set controller path.

AuthController.java

package com.gangforcode.authentication.controller;
import com.gangforcode.authentication.model.User;
import com.gangforcode.authentication.repo.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/Auth")
public class AuthController {

    @Autowired
    private Repository repository;

}

Not let’s create our first method ‘registration’ here we are storing basic details of user. We are not doing any validation here we will do that in front end

Add following code in controller class, We already make email id as unique so there is no need to check if any user exist with same id , it will automatically through error if email id is already in database

@PostMapping("/newRegistration")
public ResponseEntity<?> registration(User user)
{
    try {
        User newUser = repository.save(user);
        return new ResponseEntity<User>(newUser,HttpStatus.OK);
    }
    catch (Exception e)
    {
        return new  ResponseEntity<>("User already exist", HttpStatus.CONFLICT);
    }
}

Registration is done we need to write code for login . For login request let’s create one more model login named ‘loginModel’ with two fields emailID and password;

loginModel.java

package com.gangforcode.authentication.model;

import lombok.Data;

@Data
public class loginModel {
private String emailId;
private String password;
}

now create a method login in controller class with request body type ‘loginModel’ here we are just verifying that email id and respective password is correct or not. Add following code in controller class

@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody loginModel login){
User user = null;
user = repository.findByEmailIdAndPassword(login.getEmailId(), login.getPassword());
if(user==null)
return new ResponseEntity<>("Incorrect Credentials", HttpStatus.CONFLICT);
else
return new ResponseEntity<>(user,HttpStatus.OK);
}

We will also generate jwt token also but for now registration and login method is implemented. Now we can test login and registration end points through postman.

1 thought on “User Authentication Service Using Spring Boot”

Leave a Comment