Skip to main content

Command Palette

Search for a command to run...

Implementing Spring Security | Simple Authentication using BCryptPasswordEncoder

Published
2 min read
P

Experienced Spring Boot Developer with over 3+ years of expertise in developing scalable and high-performance web applications and microservices. Proficient in Java and Spring Boot frameworks, with hands- on experience in RESTful APIs and Microservices architecture. Adept at building secure, database-driven applications and integrating various third- party services. Strong problem-solving skills with a focus on delivering clean, maintainable, and efficient code.

Let’s start with a very basic project which has a simple @RestController UserControler. UserControler has a method mapped with @GetMapping which returns String “Hello, World!” when api ( http://localhost:8020/api/hello ) is hit.

Step 1 → Add dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
</dependency>

After adding the dependency and restarting the application you will get -

  1. A password generated by spring security for login in the console.

  2. A login page if you try to login by web.

You can use username as “user” and the password provided in the console to login.

Further you can set you own username and password by mentioning then in the properties file.

spring.security.user.name=pratt
spring.security.user.password=password@123

Step 3 → Telling Spring to read username and password from database and encrypting password.

To do this you just need to create a config class (AppConfig.java) and implement below three methods.

package com.scm.Contact.Manager.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class AppConfig {

    @Bean
    public UserDetailsService userDetailsService() {

        UserDetails userDetails1 = User.builder()
                    .username("USER")
                    .password(passwordEncoder().encode("Password@123"))
                    .roles("ADMIN")
                    .build();

        UserDetails userDetails2 = User.builder()
                    .username("pratt")
                    .password(passwordEncoder().encode("pratt"))
                    .roles("USER")
                    .build();

        return new InMemoryUserDetailsManager(userDetails1, userDetails2);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration builder) throws Exception {
        return builder.getAuthenticationManager();
    }
}

The Users has been defined inside method “userDetailsService“. These users are then loaded in “InMemoryUserDetailsManager”. Spring Security matches the user details inside request body passed to the controller to the users inside InMemoryUserDetailsManager to validate user.

Lastly, instead of creating users we can use CRUD mechanism using Spring Data JPA and load users form database and then load them to InMemoryUserDetailsManager. This way we can store user details in database.