问题描述
由于我从1.x迁移到Spring Boot 2.0.5,无意禁用安全性,所以我无法让测试角色在模拟MVC测试中工作:
Since I migrated to Spring Boot 2.0.5 from 1.x, with no mean to disable security, I can't get test roles to work on mock MVC tests :
@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!
...
我的控制器端点甚至没有受到保护!
My controller endpoint isn't even protected!
@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),但是我的请求被拒绝了,我不明白我在做什么错误的.谢谢任何想法!
So I have in the test a session (#authenticated fails when @WithMockUser is commented out) and a role by the way (ROLE_ADMIN is visible in traces) but my request is being rejected and I don't understand what I did wrong.Thx for any idea!
推荐答案
好吧……那是CSRF的好东西,然后...
Ok... the good old CSRF stuff, then...
logging.level.org.springframework.security=DEBUG
2018-10-02 10:11:41.285调试12992 --- [main] ossecurity.web.csrf.CsrfFilter:为 http://localhost/applications/foo
2018-10-02 10:11:41.285 DEBUG 12992 --- [ main] o.s.security.web.csrf.CsrfFilter : Invalid CSRF token found for http://localhost/applications/foo
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!
这篇关于Spring Boot 2,Spring Security 5和@WithMockUser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!