【问题标题】:Spring boot json error media type and spring securitySpring boot json错误媒体类型和spring security
【发布时间】:2017-01-24 16:16:29
【问题描述】:

我有一个声明为 produces = "text/plain" 的 Spring Boot (tomcat) REST 控制器。我的应用程序使用弹簧安全性。如果我发送一个会导致 403 的请求,那么默认的 Spring Boot json 错误处理程序将尝试返回 Content-Typeapplication/json

这会导致客户端实际上收到406 错误org.springframework.web.HttpMediaTypeNotAcceptableException,因为客户端在请求中指定了Accept: text/plain

显而易见的答案是要求客户端指定两个带有text/plainapplication/jsonAccept 标头。不起作用,你仍然得到406。也不适用于以逗号分隔的单个多值标头。

在所有情况下,403 与请求中的两个 Accept 标头一起一直存在到 StandardHostValve.status(),但在默认错误页面转发器中的某处失败。

有什么想法吗?

【问题讨论】:

  • 如果您的客户端在接受请求标头中仅包含application/json,它是否有效?
  • 当方法本身产生application/json时它会这样做。如果它产生其他任何东西,那么不会,结果是 406 - 这是在 403 之前生成的。
  • 嗨@AndyBrown,我正面临同样的问题。你还记得你是怎么解决的吗?
  • @y.luis 我们将两个可能的值都添加到了生产字段。即produces = {APPLICATION_JSON_UTF8_VALUE, TEXT_PLAIN_VALUE}。这对你有用吗?
  • 感谢您的快速回复@AndyBrown。我选择了另一种解决方案,我将其描述为一个答案,以防它适用于其他人。

标签: java json spring security spring-boot


【解决方案1】:

基于this solution,我所做的是添加一个自定义AccessDeniedHandler,它设置响应状态并写入它:

@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {

        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().write(accessDeniedException.getMessage());
    }
}

并在WebSecurityConfigurerAdapter上进行配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ApiWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    //...

    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic()
            .authenticationEntryPoint(authenticationEntryPoint).and().exceptionHandling().accessDeniedHandler(customAccessDeniedHandler);
    }
}

因此在 Accept 请求标头上独立返回 Content-Type: text/plain

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 2017-09-22
    • 2020-11-03
    • 2022-06-17
    • 1970-01-01
    • 2017-06-21
    • 2014-02-16
    相关资源
    最近更新 更多