Quick revision
The short answer
With MockMvc and Spring Security's test support, we annotate one test with @WithMockUser(roles = "USER") and expect isForbidden(), another with @WithMockUser(roles = "ADMIN") and expect isOk(), or set the user per request with with(user("a").roles("ADMIN")). For the POST, we send with(csrf()) to include a valid token and check that the same request without it is rejected. We also test that an unauthenticated request gets 401 or a redirect to login, depending on the configuration, and make sure the slice actually loads our security configuration.
What to remember
In this answer, we tested a Spring Security protected endpoint with MockMvc in a @WebMvcTest slice that imports our security configuration. @WithMockUser with roles USER and ADMIN, or with(user(...).roles(...)), gave 403 and 200. For the POST, with(csrf()) supplied a valid token, and the same request without it was rejected with 403. Anonymous requests got 401 with HTTP Basic, or a redirect to login with form login.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
With MockMvc and Spring Security's test support, we annotate one test with @WithMockUser(roles = "USER") and expect isForbidden(), another with @WithMockUser(roles = "ADMIN") and expect isOk(), or set the user per request with with(user("a").roles("ADMIN")). For the POST, we send with(csrf()) to include a valid token and check that the same request without it is rejected. We also test that an unauthenticated request gets 401 or a redirect to login, depending on the configuration, and make sure the slice actually loads our security configuration.
Why this question is asked
Authorization rules are some of the most important lines in an application and some of the easiest to break silently: a reordered matcher or a refactored path can open an admin endpoint to everyone. Tests are the only reliable guard. Interviewers ask this to see whether we know Spring Security's test tools and whether we test the negative cases, not just that admins get in. In this answer, we will look at the configuration under test, set up the test so it really uses that configuration, test role-based access, test CSRF on a POST, and test anonymous access.
1The Security Configuration Under Test
Our application allows only admins to reach /admin/**, requires authentication everywhere else, and uses HTTP Basic. CSRF protection, a defence against another site making the user's browser send a state-changing request, is enabled by default, so POST requests need a valid CSRF token.
Notice that hasRole("ADMIN") checks for the authority ROLE_ADMIN. @WithMockUser(roles = "ADMIN") adds that prefix for us, which is why the two line up.
2Setting Up the Test So It Uses Our Rules
@WebMvcTest starts only the web layer. Spring Boot applies security auto-configuration and builds MockMvc with the security filter chain, but our SecurityConfig is a @Configuration class, which the slice's scanning does not include. Without it the test would run against Boot's default security instead of our rules and could pass for the wrong reason. So we import it explicitly; check what your slice loads in your version.
The static imports we need are get and post from MockMvcRequestBuilders, status from MockMvcResultMatchers, and user and csrf from SecurityMockMvcRequestPostProcessors.
3Testing 403 for a User and 200 for an Admin
@WithMockUser runs a test with a fake authenticated user already in the security context, with the roles we give it. No password and no real user store are involved.
- Authenticated?YesCheck the roleNo401 with HTTP Basic, or redirect with form login
- Has ROLE_ADMIN for /admin/**?YesContinueNo403 Forbidden
- Unsafe method like POST?YesCheck the CSRF tokenNoRun the controller
- Valid CSRF token?YesRun the controllerNo403 Forbidden
4 steps in order. Play them, or step through them one at a time.
The request post-processor style, with(user(...)), sets the user per request, which is handy when one test needs several users or when the user is built from test data. Both styles produce the same security context.
4Testing That a POST Requires a CSRF Token
Even an admin's POST must carry a valid CSRF token. The csrf() post-processor adds a valid token to the request. We test both sides: with the token the request succeeds, without it the request is rejected with 403.
The negative test is the valuable one: it fails if someone disables CSRF protection by accident. If CSRF is deliberately turned off, for example for a stateless API using bearer tokens, the test should change to document that decision.
5Testing Anonymous Access
Finally, a request with no user at all. With HTTP Basic, Spring Security answers 401 Unauthorized with a WWW-Authenticate header. With form login, it answers 302 and redirects to the login page instead. The test should assert whichever the configuration promises.
Together these tests cover the full matrix: anonymous, wrong role, right role, and a state-changing request with and without CSRF. Each one fails loudly if a future change weakens the rules.
6Follow-up questions
What is the difference between 401 and 403 here?
401 means the request is not authenticated, so Spring Security asks for credentials. 403 means the user is authenticated but not allowed, either because of the role or because the CSRF token is missing or invalid.
Should security be tested with @SpringBootTest instead?
Rules for individual endpoints are best tested in the @WebMvcTest slice with the real configuration imported, because it is fast. A few @SpringBootTest tests are still useful to check that the full application wires security the same way, especially with custom filters or authentication providers.
How do you test with a real JWT?
Spring Security's test support offers a jwt() post-processor that builds an authenticated JWT with chosen claims and authorities, so we can test resource-server rules without an identity provider.
7Conclusion
In this answer, we tested a Spring Security protected endpoint with MockMvc in a @WebMvcTest slice that imports our security configuration. @WithMockUser with roles USER and ADMIN, or with(user(...).roles(...)), gave 403 and 200. For the POST, with(csrf()) supplied a valid token, and the same request without it was rejected with 403. Anonymous requests got 401 with HTTP Basic, or a redirect to login with form login.
Open with
I would write a @WebMvcTest for the admin controller, mock its service with @MockitoBean, and import my SecurityConfig, because the slice applies security auto-configuration but does not scan configuration classes, so without the import I might be testing Boot's defaults instead of my rules.
Then, if they want more
Then one test with @WithMockUser roles USER calls get on /admin/users and expects isForbidden, and another with roles ADMIN expects isOk. The annotation adds the ROLE_ prefix, which matches hasRole ADMIN in the config. Alternatively I can set the user on the request with the post-processor with user ann roles ADMIN, which is useful when one test needs different users.
For the POST, I send it as an admin with with csrf, which adds a valid token, and expect 201; then I send the same request without csrf and expect 403, and verify the service was never called, so the test fails if someone disables CSRF by accident.
I would also test an anonymous request: with HTTP Basic that is 401, with form login it is a 302 redirect to the login page, depending on the configuration. That gives the full matrix of anonymous, wrong role, right role, and CSRF present or missing.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Boot reference, Testing
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "How would you test that GET /admin/users returns 403 for a normal user and 200 for an...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/bba63997ff/