Tho*_*lan 6 spring spring-mvc spring-security spring-mvc-test spring-boot
由于我从 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!
...
Run Code Online (Sandbox Code Playgroud)
我的控制器端点甚至没有受到保护!
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
所以我在测试中有一个会话(当@WithMockUser 被注释掉时#authenticated 失败)和一个角色(ROLE_ADMIN 在跟踪中可见)但是我的请求被拒绝了,我不明白我做错了什么。谢谢你的任何想法!
好的……好的旧CSRF东西,然后……
logging.level.org.springframework.security=DEBUG
Run Code Online (Sandbox Code Playgroud)
2018-10-02 10:11:41.285 DEBUG 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!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1913 次 |
| 最近记录: |