【发布时间】:2019-08-23 14:54:49
【问题描述】:
在我的 Spring Boot 项目中添加 Spring Security(没有真正配置它来做任何事情)后,集成测试失败并出现以下错误:
java.lang.AssertionError: Response body was not valid JSON: <CustomResponse><content><id>dde6fd40-0ca3-482b-9a8e-b05fdab1b7b6</id><domain>somedomain.com</domain></content></CustomResponse>
在将 Spring Security 添加到项目之前,我的响应正文已被适当地序列化为 JSON。
我一直在搜索 Spring Security 文档以了解任何响应主体和客户端之间发生了什么,但我无法弄清楚为什么 Spring Security 可能会干扰 RestController 如何对其进行序列化。
这是我的 RestController 的示例:
@RestController
@RequestMapping("example-mapping")
@AllArgsConstructor
public class ExampleController {
private final ExampleService exampleService;
@GetMapping("/example")
public CustomResponse<ExampleDTO> checkOut(@RequestParam("domain") String domain) {
ExampleEntity result = exampleService.checkOut(domain);
return new CustomResponse<>(new ExampleDTO(result));
}
}
这是我的准系统,没有任何安全配置:
@Configuration
@AllArgsConstructor
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private AuthenticationFilter authenticationFilter;
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(authenticationFilter, BasicAuthenticationFilter.class)
.httpBasic().disable();
}
}
这是我的准系统,没有任何身份验证过滤器:
@Component
@AllArgsConstructor
public class AuthenticationFilter extends OncePerRequestFilter {
private ObjectMapper objectMapper; // injecting a global object mapper to read headers
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
// Read some headers, but currently not doing anything
filterChain.doFilter(request, response);
}
}
编辑:查看响应的Content-Type 后,它的application/xml (DUH)。那么问题来了,auth 过滤器在哪里设置响应为 XML?
编辑:将@GetMapping("/example") 更改为@GetMapping(value = "/example", produces = "application/json") 修复了序列化问题。有没有办法让它们都默认生成 JSON?
【问题讨论】:
标签: java spring spring-boot serialization spring-security