Spring Framework Spring Security & Testing 2 — Questions and Answers
Question 1: What does CSRF stand for in Spring Security?
- Cross-Server Request Failure
- Cross-Site Request Forgery (Correct answer)
- Client-Side Request Filter
- Credential Security Request Framework
Correct answer: Cross-Site Request Forgery
CSRF (Cross-Site Request Forgery) is an attack where a malicious site tricks an authenticated user's browser into making unwanted requests to another site.
Question 2: How do you write a Spring MVC controller unit test that bypasses the full security filter chain?
- @WebMvcTest with @WithMockUser (Correct answer)
- @SpringBootTest with a test profile
- @ControllerTest with @MockSecurity
- @UnitTest with @DisableSecurity
Correct answer: @WebMvcTest with @WithMockUser
@WebMvcTest loads only the web layer and @WithMockUser (from Spring Security Test) injects a mock authenticated user into the SecurityContext.
Question 3: What is the purpose of Spring Security's SecurityContextHolder?
- Stores the currently authenticated user's details throughout a request (Correct answer)
- Manages database connection security
- Holds SSL certificate information
- Caches security configuration settings
Correct answer: Stores the currently authenticated user's details throughout a request
SecurityContextHolder stores the SecurityContext (which contains the Authentication object) for the current thread, making the user's identity available throughout the request lifecycle.
Question 4: Which Spring Security filter is responsible for processing form-based username/password login?
- BasicAuthenticationFilter
- UsernamePasswordAuthenticationFilter (Correct answer)
- FormLoginFilter
- AuthenticationProcessingFilter
Correct answer: UsernamePasswordAuthenticationFilter
UsernamePasswordAuthenticationFilter intercepts login form submissions, extracts credentials, and delegates to an AuthenticationManager for validation.
Question 5: What annotation in Spring Security Test gives a test method a custom user with specific roles?
- @TestUser
- @SecurityUser
- @WithMockUser (Correct answer)
- @MockPrincipal
Correct answer: @WithMockUser
@WithMockUser populates the SecurityContext with a mock user, configurable with username, roles, and authorities, without requiring actual authentication.
Question 6: What is the role of UserDetailsService in Spring Security?
- Encrypts and decrypts user passwords
- Loads user-specific data from a data source during authentication (Correct answer)
- Manages HTTP sessions for users
- Handles OAuth2 token exchange
Correct answer: Loads user-specific data from a data source during authentication
UserDetailsService is a core interface with a single loadUserByUsername() method that retrieves a UserDetails object from the application's data source.
What does CSRF stand for in Spring Security?