If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:
>> LEARN SPRING SECURITYMocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
β’ The Registration Process With Spring Security
β’ Registration β Activate a New Account by Email
β’ Spring Security Registration β Resend Verification Email
β’ Spring Security β Reset Your Password
β’ Registration β Password Strength and Rules
β’ Updating Your Password
β’ Notify User of Login From New Device or Location
1. Overview
In this tutorial, weβll discuss a critical part of the registration process, password encoding, which is basically not storing the password in plaintext.
There are a few encoding mechanisms supported by Spring Security, and for this tutorial, weβll use BCrypt, as itβs usually the best solution available.
Most of the other mechanisms, such as the MD5PasswordEncoder and ShaPasswordEncoder, use weaker algorithms and are now deprecated.
Further reading:
New Password Storage in Spring Security
Allow Authentication from Accepted Locations Only with Spring Security
Spring Security - Auto Login User After Registration
2. Define the Password Encoder
Weβll start by defining the simple BCryptPasswordEncoder as a bean in our configuration:
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
Older implementations, such as SHAPasswordEncoder, require the client to pass in a salt value when encoding the password.
BCrypt, however, will internally generate a random salt instead. This is important to understand because it means that each call will have a different result, so we only need to encode the password once.
To make this random salt generation work, BCrypt will store the salt inside the hash value itself. For instance, the following hash value:
$2a$10$ZLhnHxdpHETcxmtEStgpI./Ri1mksgJ9iDP36FmfMdYyVg9g0b2dq
Separates three fields by $:
- The β2aβ represents the BCrypt algorithm version
- The β10β represents the strength of the algorithm
- The βZLhnHxdpHETcxmtEStgpI.β part is actually the randomly generated salt. Basically, the first 22 characters are salt. The remaining part of the last field is the actual hashed version of the plain text.
Also, be aware that the BCrypt algorithm generates a String of length 60, so we need to make sure that the password will be stored in a column that can accommodate it. A common mistake is to create a column of a different length, and then get an Invalid Username or Password error at authentication time.
3. Encode the Password on Registration
Weβll use the PasswordEncoder in our UserService to hash the password during the user registration process:
Example 3.1. The UserService Hashes the Password
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException {
if (emailExist(accountDto.getEmail())) {
throw new EmailExistsException(
"There is an account with that email adress:" + accountDto.getEmail());
}
User user = new User();
user.setFirstName(accountDto.getFirstName());
user.setLastName(accountDto.getLastName());
user.setPassword(passwordEncoder.encode(accountDto.getPassword()));
user.setEmail(accountDto.getEmail());
user.setRole(new Role(Integer.valueOf(1), user));
return repository.save(user);
}
4. Encode the Password on Authentication
Now weβll handle the other half of this process and encode the password when the user authenticates.
First, we need to inject the password encoder bean we defined earlier into our authentication provider:
@Autowired
private UserDetailsService userDetailsService;
@Bean
public DaoAuthenticationProvider authProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(encoder());
return authProvider;
}
The security configuration is simple:
- we inject our implementation of the users details service
- we define an authentication provider that references our details service
- we also enable the password encoder
Finally, we need to reference this auth provider in our security XML configuration:
<authentication-manager>
<authentication-provider ref="authProvider" />
</authentication-manager>
Or, if weβre using Java configuration:
@Configuration
@ComponentScan(basePackages = { "com.baeldung.security" })
@EnableWebSecurity
public class SecSecurityConfig {
@Bean
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.authenticationProvider(authProvider())
.build();
}
...
}
5. Conclusion
This brief article continues the Registration series by showing how to properly store the password in the database by leveraging the simple, but very powerful, BCrypt implementation.
