Skip to content
Advertisement

Spring /login?error after authorization attempt

I’m new in spring boot. Creating my own website. There was a problem logging in to the app. I’ve tried different methods, I don’t understand what the problem is. When entering an http request, this request appears http://localhost:8088/login?error and displays the Invalid email and password message in the form. The request goes through the database and everything is fine.I need it to go to the main page after logging in, which is what I tried to do.

UserService

@Service
public class UserServiceImpl implements UserService, UserDetailsService {

private final UserRepository userRepository;
private final PasswordConfig passwordConfig;
private final RoleRepository roleRepository;

@Autowired
public UserServiceImpl(UserRepository userRepository, PasswordConfig passwordConfig, 
RoleRepository roleRepository) {
   this.userRepository = userRepository;
   this.passwordConfig = passwordConfig;
   this.roleRepository = roleRepository;
}

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

   final Optional<User> user = userRepository.findByEmail(email);
   if(user.isPresent()) {
       return user.get();
   }else {
       throw new UsernameNotFoundException(MessageFormat.format("User with email {0} not 
found",email));
    }
}

@Override
public List<User> findAll() {
    return userRepository.findAll();
}

public User findUserById(Long userId) {
    Optional<User> userFromDb = userRepository.findById(userId);
    return userFromDb.orElse(new User());
}

@Override
@Transactional
public boolean signUp(User user) {
    user.setPassword(passwordConfig.getPasswordEncoder().encode(user.getPassword()));
    user.setRoles(Collections.singleton(new Role(1L, "ROLE_USER")));
    userRepository.save(user);
    return true;
}

AuthenticationController

@Controller
public class AuthenticationController {

private final UserServiceImpl userService;

@Autowired
public AuthenticationController(UserServiceImpl userService) {
    this.userService = userService;
}

@GetMapping("/registration")
public String registerPage(Model model) {
    model.addAttribute("user", new User());
    return "registration";
}

@PostMapping ("/registration")
public String registerUser(@ModelAttribute("user") @Valid User user, BindingResult 
bindingResult) {
    if (bindingResult.hasErrors()) {
        return "registration";
    }
    userService.signUp(user);
    return "login";
}

@GetMapping("/login")
public String loginPage(){
      return "login";
}

@GetMapping("/logout")
public String logoutPage() throws Exception {
      return "redirect:/";
}

WebSecurityConfig

@Configuration
@EnableWebSecurity
@ComponentScan
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

private final UserServiceImpl userService;

private final PasswordConfig passwordConfig;

private final AuthenticationSuccessHandler authSuccessHandler;

@Autowired
public WebSecurityConfig(UserServiceImpl userService, PasswordConfig passwordConfig, 
AuthenticationSuccessHandler authSuccessHandler) {
    this.userService = userService;
    this.passwordConfig = passwordConfig;
    this.authSuccessHandler = authSuccessHandler;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService).passwordEncoder(passwordConfig.getPasswordEncoder());
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService)
            .passwordEncoder(passwordConfig.getPasswordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/user/**")
        .hasRole("USER")
        .antMatchers("/admin/**")
        .hasRole("ADMIN")
        .antMatchers("/**")
        .permitAll()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/")
        .permitAll()
        .and()
        .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/login")
        .permitAll();
    http.csrf().disable();
    http.headers().frameOptions().disable();
}

login.html

<html lang="en" xmlns:th="http://www.thymeleaf.org"
  xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<title>SMS - Вход</title>

<link rel="stylesheet" type="text/css" href="/static/css/home.css" 
th:href="@{/css/signup.css}">

</head>
<body>

<div sec:authorize="isAuthenticated()" class="container has-text-centered has-text-info">
<h1>already logged in!</h1>
</div>

<div sec:authorize="isAnonymous()" class="container">
<img th:src="@{/img/SMS.JPG}" class="logo" alt="">

<form action="/login" method="POST">

    <input class="input" type="email" placeholder="email" name="username" >
    <input class="input" type="password" placeholder="password" name="password" >
    <p th:if="${param.error}" class="has-text-danger">
        Invalid email and password.
    </p>

    <input type="checkbox" checked class="checkbox" id="terms-and-cond">
    <label for="terms-and-cond">agree to our <a href="">terms and conditions</a></label>
    <br>
        <input type="checkbox" class="checkbox" id="notification">
        <label for="notification">recieve upcoming offers and events mails</a></label>
    <br>
    <button type="submit" class="submit-btn">sign in</button>
</form>
<a href="/registration" class="link">registr</a>
<a href="/" class="link">index</a>
</div>
</body>
</html>

There are no errors in the console, only:

Hibernate: select user0_.user_id as user_id1_8_, user0_.create_time as create_t2_8_, 
user0_.email as email3_8_, user0_.first_name as first_na4_8_, user0_.last_name as 
last_nam5_8_, user0_.password as password6_8_, user0_.phone_number as phone_nu7_8_ from user 
user0_ where user0_.email=?

Advertisement

Answer

I solved my problem, it helped me to add the fields enabled = true, locked = false to the User entity class

@Builder.Default
private Boolean locked = false;

@Builder.Default
private Boolean enabled = true;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement