Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Rest user repository BCCrypt password

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?

like image 688
Vijay Muvva Avatar asked May 15 '15 03:05

Vijay Muvva


2 Answers

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()));
    }
  }
}
like image 130
Javier Alvarez Avatar answered Oct 13 '22 00:10

Javier Alvarez


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.

like image 36
Manu Zi Avatar answered Oct 13 '22 00:10

Manu Zi