我有一个带有这个安全配置的Spring引导应用程序:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.headers().frameOptions().sameOrigin().and()
.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/authenticate/**", "/h2-console/**").permitAll()
.anyRequest().authenticated();
}
在我的应用程序代码中,我抛出一个ResponseStatusException:
if (existingTenant.isPresent()) {
throw new ResponseStatusException(
HttpStatusCode.valueOf(400),
"Tenant with name " + tenant.name() + " already exists");
}
但是我得到的api响应是403:
* Mark bundle as not supporting multiuse
< HTTP/1.1 403
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: SAMEORIGIN
< Content-Length: 0
< Date: Sat, 13 Aug 2022 19:26:27 GMT
<
* Connection #0 to host localhost left intact
我看到的唯一记录是:
org.springframework.web.server.ResponseStatusException: 2022-08-13T12:32:09.260-07:00警告79360 -- nio-8080-exec-6 .w.s.m.a.ResponseStatusExceptionResolver:
BAD_REQUEST 400 BAD_REQUEST“名为tenant1的租户已经存在”
为什么响应没有得到我在异常中设置的400
响应代码?
发布于 2022-08-13 22:10:05
问题是春季启动是在启用ErrorMvcAutoConfiguration的情况下提供的。我看到的403错误是因为抛出异常时的默认行为是将/error
页面服务为anonymous
用户。在我看来,这与一个新用户如何配置他们的网络安全没有很好的交互作用。我能够通过更改安全配置来允许匿名访问/error
页面来解决这个问题。
我只能通过在AffirmativeBased#decide
中添加断点并检查请求,找出出了什么问题。我注意到这个请求是/error
的,而不是原始的url,所以我能够对正在发生的事情做一些有根据的猜测。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.headers().frameOptions().sameOrigin().and()
.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/authenticate/**", "/h2-console/**").permitAll()
// ---------------------------------------------
.antMatchers("/error").anonymous() // <----- Fix
.anyRequest().authenticated();
}
处理此问题的另一种方法是在任何有@SpringBootApplication
的地方添加这个注释,从而禁用自动配置。
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
https://stackoverflow.com/questions/73347169
复制相似问题