簡體   English   中英

使用帶有 Spring Security v3.0.0 和 Thymeleaf 的 csrf 出現意外錯誤(類型=禁止,狀態=403)

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

我嘗試配置我的應用程序的安全性,但出現“意外錯誤(類型=Forbidden,狀態=403)”並且我不知道是什么問題。 我注冊一個用戶然后登錄,在“/設計”頁面上做一些事情,按提交並得到錯誤。 據我所知(來自行動書中的 Spring)Thymeleaf 自動為每個 html 頁面包含帶有 CSRF 令牌的隱藏字段。

當我在 SecurityFilterChain 中禁用 csrf 時,我的 web 應用程序工作正常。 我的SecurityConfig class如下圖:我只排除了H2Console路徑。

@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();
    }
}

感謝@dsp_user 通過添加thymeleaf-extras-springsecurity5依賴解決了問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM