Spring Boot 2,Spring Security 5和@WithMockUser


问题内容

由于我是从1.x迁移到Spring Boot 2.0.5的,无意禁用安全性,因此我无法让测试角色在模拟MVC测试中工作:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationsControllerShould {
    ...
    @Autowired
    private MockMvc mockMvc;
    private ObjectMapper mapper = new ObjectMapper();

    @Test
    @WithMockUser(roles = "ADMIN")
    public void handle_CRUD_for_applications() throws Exception {
        Application app = Application.builder()
                .code(APP_CODE).name(APP_NAME)
                .build();
        mockMvc.perform(post("/applications")
                .accept(MediaType.APPLICATION_JSON_UTF8)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(mapper.writeValueAsString(app)))
                .andExpect(authenticated())
                .andExpect(status().isOk());    // failure 403!
...

我的控制器端点甚至没有受到保护!

@RestController
@RequestMapping("/applications")
public class ApplicationsController {
    ...
    @PostMapping
    public Application addApplication(@RequestBody Application application) {
        Assert.isTrue(!applicationsDao.existsById(application.getCode()), "Application code already exists: " + application.getCode());
        return applicationsDao.save(application);
    }
}

因此,我在测试中有一个会话(当@WithMockUser被注释掉时,#authenticated失败)和一个角色(在跟踪中可见ROLE_ADMIN),但是我的请求被拒绝了,我不明白我做错了什么。感谢任何想法!


问题答案:

好吧,那是旧的CSRF好东西,然后…

logging.level.org.springframework.security=DEBUG

2018-10-02 10:11:41.285调试12992–[main]
ossecurity.web.csrf.CsrfFilter:为http:// localhost / applications /
foo
找到无效的CSRF令牌

    Application app = Application.builder()
            .code(APP_CODE).name(APP_NAME)
            .build();
    mockMvc.perform(post("/applications").with(csrf())    // oups...
            .accept(MediaType.APPLICATION_JSON_UTF8)
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(mapper.writeValueAsString(app)))
            .andExpect(authenticated())
            .andExpect(status().isOk());    // there we go!