我有一个简单的REST/API Spring bootstrap 项目,当有一个错误的模式输入时需要测试,例如:
curl -D- -X POST -H 'Content-Type: application/json' \
-d 'BAD-SCHEMA-$@#%{[|!/-' \
http://127.0.0.1:8080/auth/sign-up
我try 在测试计划中使用本机JUnit5 for Spring测试的RestTemplate
:
@Test
public void signUpBadInputSchemaValidation() {
/*
curl -D- -X POST -H 'Content-Type: application/json' \
-d 'BAD-SCHEMA-$@#%{[|!/-' \
http://127.0.0.1:8080/auth/sign-up
*/
// Prepare request headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// Prepare request body
HttpEntity<String> requestEntity = new HttpEntity<>("BAD-SCHEMA-$@#%{[|!/-");
// Create http request
ResponseEntity<Object> responseEntity = restTemplate.exchange(
"http://127.0.0.1:" + port + "/auth/sign-up",
HttpMethod.POST, requestEntity, Object.class);
// Response validation
assertThat(responseEntity.getStatusCode())
.isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY);
}
但restTemplate
自动将Content-Type
改为text/plain
,但需要保留application/json
.
我try 在测试请求中更改端口,并使用Netcat进行嗅探:
ncat -vlp 9999
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::9999
Ncat: Listening on 0.0.0.0:9999
Ncat: Connection from 127.0.0.1.
Ncat: Connection from 127.0.0.1:54478.
POST /system/access/first HTTP/1.1
Accept: application/json, application/*+json
Content-Type: text/plain;charset=UTF-8
User-Agent: Java/17.0.8
Host: 127.0.0.1:9999
Connection: keep-alive
Content-Length: 21
BAD-SCHEMA-$@#%{[|!/-
restTemplate
将标题更改为Content-Type: text/plain;charset=UTF-8
.
如何保持application/json
与明文体使用restTemplate
来执行安全测试?