LoginSignup
4
6

More than 5 years have passed since last update.

MockMvcを使ったControllerのUnitTestでCsrfトークンをRequestする

Last updated at Posted at 2016-11-15

概要

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()),
    )
}

参考

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6