Spring Boot 2,Spring Security 5和@WithMockUser

6

自从我从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);
    }
}

我在测试中使用了会话(#authenticated在去掉@WithMockUser注释后失效)和角色(ROLE_ADMIN在跟踪中可见),但是我的请求被拒绝了,我不明白哪里出了问题。 感谢任何意见!

1个回答

8

好的...那么让我们谈谈常规的CSRF问题...

logging.level.org.springframework.security=DEBUG

2018-10-02 10:11:41.285 调试信息 12992 --- [主线程] o.s.security.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!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接