【问题标题】:Unexpected error (type=Forbidden, status=403) using csrf with Spring Security v3.0.0 and Thymeleaf将 csrf 与 Spring Security v3.0.0 和 Thymeleaf 一起使用时出现意外错误(类型=禁止,状态=403)
【发布时间】:2022-12-14 18:11:29
【问题描述】:

我尝试配置我的应用程序的安全性,但出现“意外错误(类型=Forbidden,状态=403)”并且我不知道是什么问题。我注册一个用户然后登录,在“/设计”页面上做一些事情,按提交并得到错误。据我所知(来自《Spring in Action》一书)Thymeleaf 会自动为每个 html 页面包含带有 CSRF 令牌的隐藏字段。

当我在 SecurityFilterChain 中禁用 csrf 时,我的 Web 应用程序工作正常。我的 SecurityConfig 类如下所示:我只排除 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();
    }
}

【问题讨论】:

  • 那是一个 Maven 项目吗?如果是这样,您的 pom 中是否有 <artifactId>thymeleaf-extras-springsecurity5</artifactId>?
  • @dsp_user,谢谢,但我试图添加它,但由于某种原因,maven 找不到依赖项
  • 那是另一个问题,您可以为此发布一个单独的问题。不过,我认为您需要这种依赖性。

标签: java spring-security thymeleaf spring-3


【解决方案1】:

感谢@dsp_user。 添加thymeleaf-extras-springsecurity5依赖解决问题

【讨论】:

    猜你喜欢
    • 2020-10-27
    • 2019-11-27
    • 2017-11-11
    • 1970-01-01
    • 2018-01-14
    • 2020-10-10
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    相关资源
    最近更新 更多