此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.4.3spring-doc.cadn.net.cn

设置 MockMvc 和 Spring Security性

为了将 Spring Security 与 Spring MVC Test 一起使用,有必要添加 Spring SecurityFilterChainProxy作为Filter. 还需要添加 Spring Security 的TestSecurityContextHolderPostProcessor以支持在 Spring MVC Test with Comments 中以用户身份运行。 这可以使用 Spring Security 的SecurityMockMvcConfigurers.springSecurity(). 例如:spring-doc.cadn.net.cn

Spring Security 的测试支持需要spring-test-4.1.3.RELEASE或更高版本。
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SecurityConfig.class)
@WebAppConfiguration
public class CsrfShowcaseTests {

	@Autowired
	private WebApplicationContext context;

	private MockMvc mvc;

	@BeforeEach
	public void setup() {
		mvc = MockMvcBuilders
				.webAppContextSetup(context)
				.apply(springSecurity()) (1)
				.build();
	}

...
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = [SecurityConfig::class])
@WebAppConfiguration
class CsrfShowcaseTests {

    @Autowired
    private lateinit var context: WebApplicationContext

    private var mvc: MockMvc? = null

    @BeforeEach
    fun setup() {
        mvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply<DefaultMockMvcBuilder>(springSecurity()) (1)
            .build()
    }
// ...
1 SecurityMockMvcConfigurers.springSecurity() will perform all of the initial setup we need to integrate Spring Security with Spring MVC Test