Here is a controller method for user registration:
@PostMapping("register_user")
public void registerUser(@RequestParam String email, @RequestParam String password, @RequestParam String name,
@RequestParam String info, HttpServletResponse response) throws EmailExistsException, IOException {
userRepository.save(new User(email, new BCryptPasswordEncoder().encode(password), name, info));
try {
UserDetails userDetails = customUserDetailsService.loadUserByUsername(email);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
authenticationManager.authenticate(usernamePasswordAuthenticationToken);
if (usernamePasswordAuthenticationToken.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
log.debug(String.format("Auto login %s successfully!", email));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
response.sendRedirect("/");
}
Here is a configure method from SecurityConfig:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
During user registration there is a "Bad credentials" error:
org.springframework.security.authentication.BadCredentialsException: Bad credentials
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:98) ~[spring-security-core-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:166) ~[spring-security-core-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-4.1.3.RELEASE.jar:4.1.3.RELEASE]
at s7.controller.ActionController.registerUser(ActionController.java:45) ~[main/:na]
After registration user can login without any errors. What am I doing wrong?
P.S. I also tried auto login like this topic: Auto login after successful registration But I have the same BadCredentialsException.
If I comment authenticationManager.authenticate(usernamePasswordAuthenticationToken);, user will auto login without any BadCredentialsException with correct authentication.getPrincipal().