Почему возникает ошибка авторизации Spring Security
Если перевожу проект в рест, тестирую в постман, то он и регестрирует и авторизует пользователя. А при переходе на дефолтный контроллер он не авторизует....
User class
@Entit
@Getter
@Setter
@NoArgsConstructor
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String email;
private String username;
private String password;
@Enumerated(value = EnumType.STRING)
private Role role;
private Boolean locked = false;
private Boolean enabled = true;
public User(String email, String username, String password, Role role) {
this.email = email;
this.username = username;
this.password = password;
this.role = role;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority authority =
new SimpleGrantedAuthority(role.name());
return Collections.singletonList(authority);
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return email;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return !locked;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return enabled;
}
}
UserService class
@Service
@AllArgsConstructor
public class UserService implements UserDetailsService {
private final static String USER_NOT_FOUND_MSG =
"user with email %s not found";
private final UserRepository userRepository;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return userRepository.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException(String.format(USER_NOT_FOUND_MSG, email)));
}
public String SignUpUser(User user){
boolean userExists = userRepository.findByEmail(user.getEmail()).isPresent();
if (userExists){
throw new IllegalStateException("Email already taken");
}
String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword());
user.setPassword(encodedPassword);
userRepository.save(user);
return "user signup";
}
}
SecurityConfig class
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter{
private final UserService userService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
//Доступ только для не зарегистрированных пользователей
.antMatchers("/register").not().fullyAuthenticated()
//Доступ разрешен всем пользователей
.antMatchers("/").permitAll()
//Все остальные страницы требуют аутентификации
.anyRequest().authenticated()
.and()
//Настройка для входа в систему
.formLogin()
.loginPage("/login")
.usernameParameter("email")
.passwordParameter("password")
//Перенарпавление на главную страницу после успешного входа
.defaultSuccessUrl("/", true)
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.invalidateHttpSession(true)
.logoutSuccessUrl("/")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider =
new DaoAuthenticationProvider();
provider.setPasswordEncoder(bCryptPasswordEncoder);
provider.setUserDetailsService(userService);
return provider;
}
}
RegistrationService class
@Service
@AllArgsConstructor
public class RegistrationService {
private final UserRepository userRepository;
private final UserService userService;
private final EmailValidator emailValidator;
public String register(RegistrationRequest request){
boolean isValidEmail = emailValidator.test(request.getEmail());
if (!isValidEmail){
throw new IllegalStateException("Email is not valid");
}
return userService.SignUpUser(
new User(
request.getEmail(),
request.getUsername(),
request.getPassword(),
Role.USER
)
);
}
public int enabledUser(String email){
return userRepository.enableUser(email);
}
}
RegistrationRequest class
@Getter
@AllArgsConstructor
@EqualsAndHashCode
@ToString
public class RegistrationRequest {
private String email;
private String username;
private String password;
}
login form
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Taco Cloud</title>
</head>
<body>
<h1>Login</h1>
<p>New here? Click
<a th:href="@{/register}">here</a> to register.</p>
<form method="post" th:action="@{/login}" id="login">
<label for="email">Email: </label>
<input type="text" name="email" id="email" /><br/>
<label for="password">Password: </label>
<input type="password" name="password" id="password" /><br/>
<input type="submit" value="Login"/>
</form>
</form>
</body>
</html>
registration form
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:action="@{/register}" method="post" id="register">
<label th:th:for="username">Username: </label>
<input type="text" name="username"/><br/>
<label th:for="email" name="email">Email:</label>
<input type="text" name="email"><br>
<label th:for="password">Password: </label>
<input type="password" name="password"/><br/>
<label th:for="confirm">Confirm password: </label>
<input type="password" name="password">
<input type="submit" value="Register">
</form>
</body>
</html>