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

SecurityMockMvcResultHandlers

Spring Security 提供了一些ResultHandler的实现。 为了使用 Spring Security 的ResultHandlers 实现确保使用以下静态导入:spring-doc.cadn.net.cn

import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultHandlers.*;

Exporting the SecurityContext

Often times we want to query a repository to see if some MockMvc request actually persisted in the database. In some cases our repository query uses the Spring Data Integration to filter the results based on current user’s username or any other property. Let’s see an example:spring-doc.cadn.net.cn

A repository interface:spring-doc.cadn.net.cn

private interface MessageRepository extends JpaRepository<Message, Long> {
	@Query("SELECT m.content FROM Message m WHERE m.sentBy = ?#{ principal?.name }")
	List<String> findAllUserMessages();
}

Our test scenario:spring-doc.cadn.net.cn

mvc
	.perform(post("/message")
		.content("New Message")
		.contentType(MediaType.TEXT_PLAIN)
	)
	.andExpect(status().isOk());

List<String> userMessages = messageRepository.findAllUserMessages();
assertThat(userMessages).hasSize(1);

This test won’t pass because after our request finishes, the SecurityContextHolder will be cleared out by the filter chain. We can then export the TestSecurityContextHolder to our SecurityContextHolder and use it as we want:spring-doc.cadn.net.cn

mvc
	.perform(post("/message")
		.content("New Message")
		.contentType(MediaType.TEXT_PLAIN)
	)
	.andDo(exportTestSecurityContext())
	.andExpect(status().isOk());

List<String> userMessages = messageRepository.findAllUserMessages();
assertThat(userMessages).hasSize(1);

Remember to clear the SecurityContextHolder between your tests, or it may leak amongst themspring-doc.cadn.net.cn