How do you test security configurations in Spring applications?

Testing security configurations means verifying that authentication and authorization rules actually behave as configured, using Spring Security's test support to simulate different users without a real login flow.

Key Points: • @WithMockUser simulates an authenticated user with specified roles/authorities for a test method. • @WithAnonymousUser simulates an unauthenticated request to confirm public endpoints stay open and protected ones are blocked. • MockMvc combined with spring-security-test lets you assert HTTP status codes (200, 401, 403) for secured endpoints. • Integration tests should cover both positive cases (authorized access succeeds) and negative cases (unauthorized access is rejected). • SecurityMockMvcRequestPostProcessors can attach CSRF tokens or custom authentication objects to requests.

Example: A test calls mockMvc.perform(get("/admin/reports")) with @WithMockUser(roles = "USER") and asserts a 403 Forbidden, then repeats it with roles = "ADMIN" and asserts 200 OK.

Code Example:

@Test
@WithMockUser(roles = "ADMIN")
void adminCanAccessReports() throws Exception {
    mockMvc.perform(get("/admin/reports"))
           .andExpect(status().isOk());
}

@Test
void anonymousUserIsRejected() throws Exception {
    mockMvc.perform(get("/admin/reports"))
           .andExpect(status().isUnauthorized());
}

Interview Tip: A concise interview answer is:

"I test security configs using Spring Security's test support, mainly @WithMockUser to simulate users with different roles and MockMvc to hit secured endpoints and assert the expected status codes. This lets me verify authorization rules are enforced correctly without standing up a real authentication server."