I have a spring data rest custom user repository in which password need to be encrypted using BCCrypt. From the UI I am sending the plain password, I want to know where to convert the plain password into BCCrypt hash before hibernate creates user in DB. Should I use before save interceptor and hash the password? Or is there any way I can tell spring to use password encoder?
The way to intercept inserts in Spring Data Rest is using an event handler.
NOTE: This code won't work with PATCH operations that don't include the password field.
@Component
@RepositoryEventHandler(User.class)
public class UserEventHandler {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Autowired
private UserRepository userRepository;
@HandleBeforeCreate
public void handleUserCreate(User user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
}
@HandleBeforeSave
public void handleUserUpdate(User user) {
if (user.getPassword() == null || user.getPassword().equals("")) {
//keeps the last password
User storedUser = userRepository.getOne(user.getId());
user.setPassword(storedUser.getPassword());
}
else {
//password change request
user.setPassword(passwordEncoder.encode(user.getPassword()));
}
}
}
You need to do it in your Registration-Service
, like the following:
@Autowired
private BCryptPasswordEncoder passwordEncoder;
...
public void registerUser(final User user)
{
final String encodedPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(encodedPassword);
userRepo.save(user);
}
The password-encoder i refer you, is the org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
this encoder automatically generate a salt for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With