Spring Security Test provides comprehensive testing utilities for Spring Security applications with mock authentication, security context testing, and web security testing features.
npx @tessl/cli install tessl/maven-org-springframework-security--spring-security-test@6.5.0Spring Security Test provides comprehensive testing utilities for Spring Security applications, enabling developers to easily test authentication, authorization, and security configurations. It offers mock authentication support through annotations, declarative security context management, and utilities for testing both servlet-based and reactive Spring applications.
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>6.5.1</version>
<scope>test</scope>
</dependency>For Gradle:
testImplementation 'org.springframework.security:spring-security-test:6.5.1'import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithUserDetails;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureTestDatabase
public class SecurityTestExample {
@Autowired
private MockMvc mockMvc;
// Using annotation-based authentication
@Test
@WithMockUser(roles = "ADMIN")
public void testAdminEndpoint() throws Exception {
mockMvc.perform(get("/admin"))
.andExpect(status().isOk());
}
// Using request post-processors
@Test
public void testWithRequestPostProcessor() throws Exception {
mockMvc.perform(get("/secure")
.with(user("testuser").roles("USER")))
.andExpect(status().isOk());
}
}Spring Security Test is built around several key components:
@WithMockUser that establish security contexts declarativelyCore testing annotations for declarative security context management, providing method and class-level authentication setup without complex configuration.
@WithMockUser(username = "user", roles = {"USER"}, authorities = {})
@WithAnonymousUser
@WithUserDetails(value = "user", userDetailsServiceBeanName = "")
@WithSecurityContext(factory = WithSecurityContextFactory.class)Comprehensive MockMvc integration providing request post-processors, configurers, and result matchers for testing web security in servlet-based applications.
// Setup
MockMvcConfigurer springSecurity();
// Request post-processors
RequestPostProcessor user(String username);
RequestPostProcessor httpBasic(String username, String password);
RequestPostProcessor jwt();
RequestPostProcessor csrf();
// Result matchers
ResultMatcher authenticated();
ResultMatcher unauthenticated();WebTestClient integration for testing security in reactive Spring WebFlux applications, providing mutators for various authentication scenarios.
// Server configurers
MockServerConfigurer springSecurity();
// Authentication mutators
UserExchangeMutator mockUser();
JwtMutator mockJwt();
OAuth2LoginMutator mockOAuth2Login();
CsrfMutator csrf();Low-level utilities for programmatic security context management and integration with Spring Test framework execution listeners.
class TestSecurityContextHolder {
static void setContext(SecurityContext context);
static SecurityContext getContext();
static void clearContext();
static void setAuthentication(Authentication authentication);
}enum TestExecutionEvent {
TEST_METHOD,
TEST_EXECUTION
}
interface WithSecurityContextFactory<A extends Annotation> {
SecurityContext createSecurityContext(A annotation);
}
interface AuthenticatedMatcher extends ResultMatcher {
AuthenticatedMatcher withUsername(String expected);
AuthenticatedMatcher withRoles(String... roles);
AuthenticatedMatcher withAuthorities(Collection<? extends GrantedAuthority> expected);
}