Testing Spring Security (with and without Auth)
Fast recall
Quick revision
Core answer
Whether you can test security rules without involving a real authentication server or hardcoded tokens
Disabling security in tests with @WebMvcTest(excludeAutoConfiguration = SecurityAutoConfiguration.class) — this means your security rules are never tested
Demonstrate knowledge of jwt() and oidcLogin() request post-processors for OAuth2 tests, and how @WithSecurityContext enables custom security scenarios
Interview-ready guide
Interview answer
Don't disable security in tests — use @WithMockUser(roles = "ADMIN") to create mock authentication. The test should verify both paths: that authorized users can access the endpoint AND that unauthorized users are rejected. A security test that only checks the allowed path proves nothing.
For controller security, @WebMvcTest with @WithMockUser works because Spring Security auto-configuration is included in the web slice. For method-level @PreAuthorize security, you need @SpringBootTest because the security proxy is created by Spring AOP.
The critical thing to test is the denied path. A misconfigured @PreAuthorize silently allows everything. If assertThrows(AccessDeniedException.class) doesn't throw, the security rule isn't active — and the "allowed" test would still pass, hiding the bug.
For JWT or custom authentication, use @WithSecurityContext to build a custom security context with your principal and claims.
Testing Spring Security (with and without Auth)
Direct Answer
Use @WebMvcTest with Spring Security auto-configuration included. For authenticated requests, use @WithMockUser or @WithUserDetails to inject a principal into the SecurityContext without a real login flow. For JWT/OAuth2, use SecurityMockMvcRequestPostProcessors.jwt() or .oidcLogin(). Assert that protected endpoints return 401/403 for unauthenticated/unauthorised requests and 200 for correctly authorised ones.
Common Mistakes & Pitfalls
Disabling security in tests with @WebMvcTest(excludeAutoConfiguration = SecurityAutoConfiguration.class) — this means your security rules are never tested
Check your understanding
Answer these without looking back at the article.
- How do you test CSRF protection in MockMvc?
- How do you test Spring Security OAuth2 login flows?
- How do you test that a security filter is correctly applied?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.