Spring не работает форма входа /login
Я новичок в spring boot. Создаю свой сайт. Возникла проблема со входом в приложение. Перепробовал разные методы, не понимаю в чём проблема. При входе в http запросе появляется данный запрос http://localhost:8088/login?error и в форме выводит сообщение Invalid email and password. По бд запрос проходит и все нормально. Мне нужно чтобы после входа переводило на главную страницу, что я и пытался сделать.
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>
В консоле нет никаких ошибок, только:
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=?
Ответы (1 шт):
Я решил свою проблему, мне помогло в класс сущности User добавить поля enabled = true, locked = false
@Builder.Default
private Boolean locked = false;
@Builder.Default
private Boolean enabled = true;
Также не стоит забывать об имплементации интерфейса UserDetails c его методами