Encrypt User Password with Spring Security

With this short blog post, I am going to share with you how to add Spring Security to your project so that we can use Spring Security to encrypt user password.

I assume you already have your project created with Spring and in case you have not check out my blog post on “Create a very simple Web Service Project with Spring Boot“. And since you are looking for a way to encrypt user password before saving it to a database, you might be interested to check out my blog post on “Spring MVC and JPA – Save to a Database“.

Once you have your project created and hopefully with Spring Boot below is an example of how to encrypt user password using the Spring Security.

Add Spring Security to pom.xml File

I will begin by adding a Spring Security dependency to a pom.xml file of my Spring Boot project. Open pom.xml file and add the following dependency:

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

Once you add this dependency none of your Web Service API endpoints will be available unless you provide a Bearer token in the header of the request sent to a web service endpoint. 

We can configure our app and provide which Web Service URLs should not be protected with a secure token and can be accessed without an Authorization token in the header of our request.

The Sign-up URL is usually public and should not require an authorization token.  

Make the Signup URL Not Require Authorization Token

Create a new class and annotation it with @EnableWebSecurity annotation. This class must extend the WebSecurityConfigurerAdapter.

Have a look at the way the authorization is disabled for the SIGN_UP_URL for HTTP POST Request while all other URLs of your Web App will still require Authorization header and a Bearer token be provided.

package com.appsdeveloperblog.app.ws.security;

import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class ApiSecurity extends WebSecurityConfigurerAdapter {
    private final UserDetailsService userDetailsService;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;
    
    public static final String SIGN_UP_URL = "/users";

    public ApiSecurity(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeRequests().antMatchers(HttpMethod.POST, SIGN_UP_URL)
                .permitAll().anyRequest().authenticated();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }
}

Create the BCryptPasswordEncoder Bean

After you add the above-mentioned class annotated with @EnableWebSecurity you will need to make another change to your project so that the BCryptPasswordEncoder can be autowired. To do that follow the below steps:

  • Open the main class of your Spring Boot app which contains the public static void main function and which is annotated with @SpringBootApplication
  • Add the below code snippet to your class with @SpringBootApplication annotation:
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
 return new BCryptPasswordEncoder();
}

After adding the above code snippet my Spring Boot Application class looks like this:

package com.appsdeveloperblog.app.ws;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@SpringBootApplication
public class MobileAppWsApplication {

 public static void main(String[] args) {
  SpringApplication.run(MobileAppWsApplication.class, args);
 }
 
 @Bean
 public BCryptPasswordEncoder bCryptPasswordEncoder() {
  return new BCryptPasswordEncoder();
 }
}

Once you make the BCryptPasswordEncoder as an autowirable Bean you can Autowire it into your @Service class and use to encrypt the provided user password. Below is an example of my Service class and a method which makes use of BCryptPasswordEncoder to encrypt user password before it is being saved in a database.

Please note the use of bCryptPasswordEncoder.encode() function which accepts user password String and encodes it to make it safe to save its value in a database.

bCryptPasswordEncoder.encode(String)

example of createUser() function which uses the BCryptPasswordEncoder.

@Service
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    public UserServiceImpl(UserRepository userRepository,
            BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userRepository = userRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

@Override
    public UserDto createUser(UserDto userDto) {
        UserDto returnValue = new UserDto();

        ...
  
        // Generate secure password
        userDto.setEncryptedPassword(bCryptPasswordEncoder.encode(userDto.getPassword()));

        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userDto, userEntity);

        // Record data into a database
        userEntity = userRepository.save(userEntity);
 
         ...

        return returnValue;
    }

}

And this is it!

I hope this short blog post is of some value to you.

The Spring Boot Framework makes it very easy to add the Security features to your Web Service app. Encrypting password is one of these features and making your Web Service API protected with a secure access token is another feature which is very easy to configure with Spring Boot. Stay tuned and subscribe to my blog because I am above to share how to do it.

Also, below is a list of video courses which will help you learn a lot about Spring Boot. Have a look at them and hopefully one of them will be what you were looking for.