【发布时间】: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