首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么Spring ResponseStatusException 400被翻译成403

为什么Spring ResponseStatusException 400被翻译成403
EN

Stack Overflow用户
提问于 2022-08-13 19:35:46
回答 1查看 64关注 0票数 1

我有一个带有这个安全配置的Spring引导应用程序:

代码语言:javascript
运行
复制
  @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:

代码语言:javascript
运行
复制
    if (existingTenant.isPresent()) {
      throw new ResponseStatusException(
          HttpStatusCode.valueOf(400),
          "Tenant with name " + tenant.name() + " already exists");
    }

但是我得到的api响应是403:

代码语言:javascript
运行
复制
* 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响应代码?

EN

回答 1

Stack Overflow用户

发布于 2022-08-13 22:10:05

问题是春季启动是在启用ErrorMvcAutoConfiguration的情况下提供的。我看到的403错误是因为抛出异常时的默认行为是将/error页面服务为anonymous用户。在我看来,这与一个新用户如何配置他们的网络安全没有很好的交互作用。我能够通过更改安全配置来允许匿名访问/error页面来解决这个问题。

我只能通过在AffirmativeBased#decide中添加断点并检查请求,找出出了什么问题。我注意到这个请求是/error的,而不是原始的url,所以我能够对正在发生的事情做一些有根据的猜测。

代码语言:javascript
运行
复制
  @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的地方添加这个注释,从而禁用自动配置。

代码语言:javascript
运行
复制
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73347169

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档