概要
SpringSecurityを使用している場合、SpringのMockMvcを使ってControllerのテストを書く と、
PostリクエストはCSRF Tokenがないと403になってしまうので、その対応。
テスト対象メソッド
@PostMapping(value = "hoge", consumes = MediaType.APPLICATION_JSON_VALUE)
public void hoge(@RequestBody Hoge hoge) {
System.out.println("hoge");
}
spring-security-test
を依存に追加
下記はMavenの場合。
pom.xmlに追加する。
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
SecurityMockMvcRequestPostProcessors
を使う
下記はSpockでの例。
def "CSRFトークンを使ったPostリクエスト"() {
setup:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(new Hoge());
expect:
mockMvc.perform(MockMvcRequestBuilders
.post('/hoge')
.contentType(MediaType.APPLICATION_JSON)
.content(json)
// CSRFトークンをセット
.with(SecurityMockMvcRequestPostProcessors.csrf())
).andExpect(
MockMvcResultMatchers.status().is(HttpStatus.OK.value()),
)
}