[英]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.