Spring Boot ResponseBody 在实现 Spring 安全性后不会序列化为 JSON



将 Spring 安全性(没有真正配置它以执行任何操作(添加到我的 Spring 启动项目后,集成测试失败并出现以下错误:

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 安全性添加到项目中之前,我的响应主体已适当地序列化为 JSON。

我一直在搜索 Spring 安全文档,看看任何响应体和客户端之间发生了什么,但我无法弄清楚为什么 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(。所以问题是,身份验证过滤器在哪里将响应设置为 XML?

编辑:将@GetMapping("/example")更改为@GetMapping(value = "/example", produces = "application/json")修复序列化问题。有没有办法让它们默认都生成 JSON?

JSON 已经是使用spring-web设置项目时的默认内容类型。类路径中是否也有spring-security并不重要。 我创建了一个具有最少依赖项的示例项目:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

我的测试控制器默认返回 JSON:

@RestController
public class TestController {
@GetMapping("/hello")
public Map<String, String> getGreeting() {
final HashMap<String, String> result = new HashMap<>();
result.put("value", "hello");
return result;
}
}
{
"value": "hello"
}

因此,您的依赖项可能存在问题。

最新更新