I try to implement an auto-login after a successful registration in my spring-boot application.
To store the user data, I use Hibernate and for the authentication I use the DaoAuthenticationProvider. The login for users which are already in the database works well and the registration of a new user also. Only the auto-login after the registration doesn't work.
As the username I use the email of the user. I tried several different approaches that where recommended on the internet. None of them worked. Including these:
Auto login after successful registration How can I programmatically authenticate user with Spring Security using DaoAuthenticationProvider https://www.baeldung.com/spring-security-auto-login-user-after-registration
My WebSecurityConifig class:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
private UserService userService;
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth
.userDetailsService(userService)
.passwordEncoder(bCryptPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
authorizeRequests()
.antMatchers("/login", "/console/**", "/registerNewUser/**", "/resources/**", "/css/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated().and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringAntMatchers("/console/**")
// Request zum Aufruf der Login-Seite
.and().formLogin().loginPage("/login").failureUrl("/login?error=true").permitAll()
.defaultSuccessUrl("/")
.usernameParameter("email")
.passwordParameter("password")
.and().logout().permitAll()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout");
http.headers().frameOptions().sameOrigin().disable();
http.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry());
}
@Override
public void configure(WebSecurity web) {
web
.ignoring()
.antMatchers("/resources/static/**", "/css/**", "/js/**", "/img/**");
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userService);
auth.setPasswordEncoder(bCryptPasswordEncoder);
return auth;
}
@Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
@Bean
public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
}
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
My controller to register a new user:
@Controller
public class AccRegistrationController {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Autowired
private UserValidator userValidator;
@Autowired
private AuthenticationManager authenticationManager;
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setValidator(userValidator);
}
@GetMapping("registerNewUser")
public String registerUser(Model model, HttpServletRequest request) {
model.addAttribute("user", new User());
request.getSession();
return "accountRegistration/registration";
}
@PostMapping("registerNewUser")
public String registerAccount(HttpServletRequest request, @Valid @ModelAttribute("user") User user, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("user", user);
return "accountRegistration/registration";
}
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setActivated(false);
user.setRoles(roleService.findAllByRolename("ROLE_USER"));
userService.saveUser(user);
UsernamePasswordAuthenticationToken token = new
UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword());
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
token.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
return "redirect:registerNewUser?success";
}
}
My UserService class:
@Service
public class UserService implements UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(Data.class);
@Autowired
private UserRepository userRepository;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Autowired
private SessionRegistry sessionRegistry;
/* creates new user object and returns it with an auto generated id */
public User saveUser(User user) {
return userRepository.save(user);
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
public Optional<User> findUser(Integer id) {
return userRepository.findById(id);
}
public User getUserByEmail(String email) {
return userRepository.findUserByEmail(email);
}
public User getOne(Integer id) {
return userRepository.getOne(id);
}
public User getCurrentUser() {
return getUserByEmail(((org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername());
}
public org.springframework.security.core.userdetails.User getCurrentUserDetails() {
return (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findUserByEmail(email);
if (Objects.isNull(user)) {
throw new UsernameNotFoundException("Could not find the user for username " + email);
}
List<GrantedAuthority> grantedAuthorities = getUserAuthorities(user.getRoles());
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(),
user.isEnabled(), true, true, user.isEnabled(), grantedAuthorities);
}
private List<GrantedAuthority> getUserAuthorities(Set<Role> roleSet) {
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (Role role : roleSet) {
grantedAuthorities.add(new SimpleGrantedAuthority(role.getRolename()));
}
return grantedAuthorities;
}
public Collection<String> getLoggedInUsers() {
return sessionRegistry.getAllPrincipals().stream()
.filter(u -> !sessionRegistry.getAllSessions(u, false).isEmpty())
.map(Object::toString)
.collect(Collectors.toList());
}
}
I added some println-statements in the AccRegistrationController to my code to find out where the problem is because no error occurred while/after the registration process. I found out that the problem must be in this code line:
Authentication authentication = authenticationManager.authenticate(token);
But I can't say what is wrong. Probably there's something with the authenticationManager not correct.
Whatever I've noticed the "registerAccount" method is not executed to the end. The redirect doesn't work and I get redirected to the login page.
I hope you can help me to find my mistake.