首页 > 解决方案 > Spring 5 中的 .csrf() 方法现在位于哪个包中?

问题描述

我正在尝试编写 IT。

mockMvc.perform( post( "/my_endpoint" )
            .contentType( MediaType.APPLICATION_JSON )
            .header("Authorization", my_credentials)
            .with(csrf())
            .content( jsonPayload )
                )
            .andExpect( status().isOk() );

我需要导入csrf()静态方法,但是通常创建的包(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors...)不再存在。

关于如何编写 csrf 保护以避免403测试中的一些新想法?

谢谢。

标签: springspring-bootintegration-testingcsrf

解决方案


要使用 Spring Security 测试支持,您必须包含spring-security-test-5.1.2.RELEASE.jar作为项目的依赖项。并在下面试一试:-

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProce ssors.*;

mvc.perform(post("/").with(csrf()))

或者,

mvc.perform(post("/").with(csrf().asHeader()))

或者,

mvc.perform(post("/").with(csrf().useInvalidToken()))

推荐阅读