Ahoy!
I have a little problem that I've been struggling with for almost 3 days. I looked up almost all the stackoverflow answers related to this question and answers but none of them helped me solve this.
I am trying to create a login-registration web application using Spring Boot Security using MySQL and Thymeleaf.
So far my registration is working pretty well. I've got problem with the login part. I've tested the inputs in my UserServiceImpl and I got no white spaces in my input so I think my input are OK.
I run into error always when I am trying to log in. "/login?error=true"
Below you can see my project structure.
My Security Configuration:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userService);
auth.setPasswordEncoder(passwordEncoder());
return auth;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/favicon.ico", "/resources/**", "/error", "/static/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers(
"/signup",
"/kereses",
"/szallas",
"/index",
"/",
"/js/**",
"/bootstrap/**",
"/fonts/**",
"/css/**",
"/img/**",
"/static/**",
"/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable().formLogin()
.loginPage("/login")
.failureUrl("/login?error=true")
.defaultSuccessUrl("/index", true)
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.permitAll();
}
}
This is the UserServiceImpl:
@Service
public class UserServiceImpl implements UserService{
private UserRepository userRepository;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
public UserServiceImpl(UserRepository userRepository) {
super();
this.userRepository = userRepository;
}
@Override
public User save(UserRegistrationDto registrationDto) {
User user = new User(registrationDto.getKeresztnev(),
registrationDto.getVezeteknev(), registrationDto.getEmail(),
passwordEncoder.encode(registrationDto.getJelszo()), Arrays.asList(new Role("ROLE_USER")));
return userRepository.save(user);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByEmail(username);
if(user == null) {
throw new UsernameNotFoundException("Helytelen felhasználónév vagy jelszó.");
}
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getJelszo(), mapRolesToAuthorities(user.getRoles()));
}
private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles){
return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
}
}
This is my login.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>SmartHotel.com</title>
<meta name="description" content="Az elérhető árú hotelek és szállások helye. Foglalj most!">
<link rel="stylesheet" href="/bootstrap/css/bootstrap.min.css" type="text/css" crossorigin="anonymous">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet" crossorigin="anonymous">
<link rel="stylesheet" href="/fonts/font-awesome.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="/fonts/simple-line-icons.min.css" type="text/css" crossorigin="anonymous">
<link rel="stylesheet" href="/css/styles.min.css" type="text/css" crossorigin="anonymous">
<link rel="stylesheet" href="/css/login.css" type="text/css" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-light navbar-expand bg-light navigation-clean">
<div class="container"><a th:href="@{/}" class="navbar-brand">SmartHotel.com</a><button data-toggle="collapse" class="navbar-toggler" data-target="#navcol-1"></button>
<div class="collapse navbar-collapse" id="navcol-1"><a class="btn btn-primary ml-auto" role="button" th:href="@{signup}">Regisztráció</a></div>
</div>
</nav>
<div class="text-center h-100" style="background-color: white; background-size: cover;">
<div class="container">
<div class="text-center m-auto">
<!--LOGIN FORM TODO meghatarozni az actiont-->
<form th:action="@{/login}" method="post">
<h1 class="">Bejelentkezés</h1>
<div>
<!-- logout message -->
<div th:if="${param.logout}">
<div class="">Sikeresen kijelentkezés.</div>
</div>
<label for ="username" class="sr-only"> Email</label>
<input type="text" class = "form-control" id ="username" name = "username" placeholder="Email" autofocus="autofocus">
<label for="jelszo" class="sr-only">Jelszó</label>
<input type="password" id="jelszo" name="jelszo" class="form-control" placeholder="Jelszó" autocomplete="on" />
<input type="submit" name="login-submit" id="login-submit" value="Bejelentkezés" />
<span>Nincs még fiókja?<a th:href="@{/signup}">Regisztráció</a></span>
<p class="mt-5 mb-3 text-muted">© 2020</p>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
In my controller I have only this code about login because as far as I know my authentication does the login post requests.
@GetMapping("/login")
public String login() {
return "login";
}
Thanks any help in advance!
You should move this line
.anyRequest().authenticated()
To be after the line:
.logout()
Because the below line will match all request and ask for authentication
.anyRequest().authenticated()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.