Spring Security Authentication

Introduction:

In this document, we will walk you through the steps to generate Authentication & Authorization using Database | Spring Security 6.0.

Authentication: Authentication is the process of Authenticating or ensuring that an user has correct credentials to access a particular service through his/her username and password.
Authorization: Authorization ensure that this entity has the required access control rights or permissions to execute sensitive code.


Implementation

Step 0: Prerequisites/Requirements/Dependencies installation:

Before proceeding, ensure that you have the following requirements installed:

1. Spring Tool Suite (STS) or any other preferred IDE installed.
2. Java Development Kit (JDK) installed.
3. Basic knowledge of Java and Spring Boot.

** Let’s Proceed towards the project with the steps mentioned below.


Step 1: Create a Spring Boot Project

1. Open Spring Tool Suite.
2. Click on "File" -> "New" -> "Spring Starter Project."
3. Enter a project name, such as "spring-boot-QR-code."
4. Set the Group and Artifact IDs accordingly.
5. Choose the desired Java version17.
6. Click "Next" and select "Web" from the list of dependencies.
7. Click "Finish" to create the project.


Step 2: Add Dependencies

1. spring web
2. MySQL Driver
3. Thymeleaf
4. Spring Data JPA
5. Spring Security
6. SpringBoot Devtools


set Application.Properties as:
spring.datasource.url=jdbc:mysql://localhost:3306/security_db
spring.datasource.username=root
spring.datasource.password=Password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.ddl-auto=update


Step 3: Open the pom.xml file:

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity6</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Step 4: Create HTML File:

1. Index.html
2. About.html
3. Profile.html


Step 5: Create Entity file in the following file location -> src/main/java

Employee.java
package com.example.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Employee {


    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    private String name;

    private String deparment;

    private String role;
    private String email;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public String getDeparment() {
        return deparment;
    }

    public void setDeparment(String deparment) {
        this.deparment = deparment;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

Step 6: Create Controller file

package com.HomeController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String index() {
        return"index";
    }
    @GetMapping("/about")
    public String about() {
        return"about";
    }
    @GetMapping("/profile")
    public String profile() {
        return"profile";
    }
}

Step 7: Create Configuration File with the following name -> CustomUser.java

package com.example.config;
import java.util.AbstractList;
import java.util.Collection;
import java.util.Objects;
import java.util.RandomAccess;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.example.entity.Employee;
 
public class CustomUser implements UserDetails {
    private Employee emp;

    private static class ArrayList<E> extends AbstractList<E>
    implements RandomAccess, java.io.Serializable
    {  
        private static final long serialVersionUID = -2764017481108945198L;
        private final E[] a;
        ArrayList(E[] array) {
            a = Objects.requireNonNull(array);
        }

        public String getPassword() {
            // TODO Auto-generated method stub
            return null;
        }
        
        
        public String getUsername() {
            // TODO Auto-generated method stub
            return null;
        }
        
        
        public boolean isAccountNonExpired() {
            // TODO Auto-generated method stub
            return true;
        }
        
        
        public boolean isAccountNonLocked() {
            // TODO Auto-generated method stub
            return true;
        }
        
        
        public boolean isCredentialsNonExpired() {
            // TODO Auto-generated method stub
            return true;
        }
        
        
        public boolean isEnabled() {
            // TODO Auto-generated method stub
            return true;
        }
        
        @Override
        public int size() {
            // TODO Auto-generated method stub
            return 0;
        }
        
        @Override
        public boolean addAll(Collection<? extends E> c) {
            // TODO Auto-generated method stub
            return false;
        }
        
        @Override
        public E get(int index) {
            // TODO Auto-generated method stub
            return null;
        }
    }
    public CustomUser(Employee emp) {
    
    }
    
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // TODO Auto-generated method stub
        return null;
    }
    
    @Override
    public String getPassword() {
        // TODO Auto-generated method stub
        return null;
    }
    
    @Override
    public String getUsername() {
        // TODO Auto-generated method stub
        return null;
    }
    
    @Override
    public boolean isAccountNonExpired() {
        // TODO Auto-generated method stub
        return false;
    }
    
    @Override
    public boolean isAccountNonLocked() {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public boolean isCredentialsNonExpired() {
        // TODO Auto-generated method stub
        return false;
    }
    
    @Override
    public boolean isEnabled() {
        // TODO Auto-generated method stub
        return false;
    }
}

Step 8: CustomerUserDetails Service file under Configuration Package

package com.example.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.example.Repository.EmpRepo;
import com.example.entity.Employee;

@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private EmpRepo empRepo;

    @Override
    public UserDetails loadUserByUsername(String email) throws
    UsernameNotFoundException {

        Employee emp =empRepo .findByemail(email);

        if (emp==null) {
            throw new UsernameNotFoundException("user name not found");
        }
        else
        {
            return new CustomUser(emp);
        }
    
    }
    
    public CustomUserDetailsService(EmpRepo empRepo) {
        super();
        this.empRepo = empRepo;
    }
}

Step 9: Create Repository File

package com.example.Repository;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import com.example.entity.Employee;

public interface EmpRepo extends JpaRepositoryImplementation<Employee, Integer> {
    public Employee findByemail(String email);
}

Step 10: Create Security Config .java file Under Configuration Package

package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    public BCryptPasswordEncoder passwordEncoder()
    {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public UserDetailsService getUserDetailsService()
    {
        return new CustomUserDetailsService(null);
    }
    @Bean
    public DaoAuthenticationProvider authenticationprovider() {
        DaoAuthenticationProvider daoauthenticationprovider= new

        DaoAuthenticationProvider();

        daoauthenticationprovider.setUserDetailsService(getUserDetailsService());
        daoauthenticationprovider.setPasswordEncoder(passwordEncoder());
        return daoauthenticationprovider;

    }
    @Bean
    public SecurityFilterChain securityFiletChain(HttpSecurity http) throws Exception
    {
        http.csrf().disable().authorizeHttpRequests().requestMatchers("/index").permitAll().anyRequ

        est().authenticated().and().formLogin();
        return http.build();
    }

}

Results

The File Structure


img

The login Interface


img


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext