Spring Boot 2, Spring Security 5 and @WithMockUser

。_饼干妹妹 提交于 2019-12-01 22:31:10

问题


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);
    }
}

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!


回答1:


Ok... the good old CSRF stuff, then...

logging.level.org.springframework.security=DEBUG

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!


来源:https://stackoverflow.com/questions/52604164/spring-boot-2-spring-security-5-and-withmockuser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!