简体   繁体   中英

Unexpected error (type=Forbidden, status=403) using csrf with Spring Security v3.0.0 and Thymeleaf

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM