I try to configure security of my application but I get "Unexpected error (type=Forbidden, status=403)" and I don't know what is the problem. I register a user then login, do some stuff on a "/design" page, press submit and get the Error. As I know (from Spring in Action book) Thymeleaf automatically include hidden field with CSRF token for each html page.
When I disable csrf in SecurityFilterChain my web application works fine. My SecurityConfig class is shown below: I only exclude H2Console path.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
private UserRepository userRepository;
@Bean
public UserDetailsService userDetailsService(UserRepository userRepo) {
return username -> {
User user = userRepo.findByUsername(username);
if(user != null) {
return user;
}
throw new UsernameNotFoundException("User \"" + username + "\" not found");
};
}
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().ignoringRequestMatchers(PathRequest.toH2Console())
.and()
.headers((headers) -> headers.frameOptions().sameOrigin())
.authorizeHttpRequests()
.requestMatchers("/design","/orders").hasRole("USER")
.requestMatchers("/", "/**").permitAll()
.and()
.formLogin(
form -> form
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/design")
.permitAll()
).logout(
logout -> logout
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.permitAll()
);
return http.build();
}
}
Thanks to @dsp_user.
Problem solved by adding thymeleaf-extras-springsecurity5
dependency