Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
Five MockMvc tests ask the same endpoints as different people: nobody gets 401, a customer gets 403 on the agent list, an agent gets 200, Emma opens her own ticket, Noah gets 403 on hers. Plus the red test you get when @WithMockUser has no roles.
What you will learn
- Load your real SecurityConfig into a @WebMvcTest with @Import
- Write one test each for no user (401), the wrong role (403) and the right role (200)
- Put a test user in the security context with @WithMockUser
- Prove that one customer cannot open another customer's ticket
Before you start
- Spring Boot Test Slices: @WebMvcTest with MockMvc
- The Spring Security Filter Chain and Your Own Rules
When an endpoint is protected, three people matter: someone with no login at all, someone with the wrong role, and someone with the right role. Write one test for each, and each test asks for exactly one answer: 401, 403 or 200. Then add one more person, the one who has the right role but the wrong data.
The rules we're testing
The SecurityConfig holds one filter chain: /api/tickets (the full list) needs the AGENT role, any other request just needs a logged-in user, HTTP Basic is on (which is why no user at all gets a 401), and CSRF is off because this is a JSON API.
The controller adds one more check for a single ticket. It finds the ticket (404 if the id is unknown), then checks whether the caller holds ROLE_AGENT (with the prefix) or owns the ticket. If neither, it throws AccessDeniedException, and Spring Security turns that into a 403.
The test class
@WebMvcTest(TicketController.class)
@Import({SecurityConfig.class, TicketService.class})
class TicketSecurityTest {
@Autowired
private MockMvc mockMvc;
@Test
void noUserIsUnauthorized() throws Exception {
mockMvc.perform(get("/api/tickets"))
.andExpect(status().isUnauthorized());
}
@Test
@WithMockUser(username = "sam", roles = "CUSTOMER")
void aCustomerIsForbidden() throws Exception {
mockMvc.perform(get("/api/tickets"))
.andExpect(status().isForbidden());
}
@Test
@WithMockUser(username = "chaand", roles = "AGENT")
void anAgentSeesAllTickets() throws Exception {
mockMvc.perform(get("/api/tickets"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(2));
}
@Test
@WithMockUser(username = "emma", roles = "CUSTOMER")
void emmaOpensHerOwnTicket() throws Exception {
mockMvc.perform(get("/api/tickets/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Printer is offline"));
}
@Test
@WithMockUser(username = "noah", roles = "CUSTOMER")
void noahCannotOpenEmmasTicket() throws Exception {
mockMvc.perform(get("/api/tickets/1"))
.andExpect(status().isForbidden());
}
}
@WebMvcTest loads only the web layer, and @Import brings in your real SecurityConfig and the ticket service. That's the important part: the test runs the actual rules, not a copy of them. MockMvc calls the app without starting a server.
Where the test user comes from
There's no login and no password in these tests. Before the request runs, @WithMockUser(username = "sam", roles = "CUSTOMER") builds a user and puts it straight into the security context, the place that knows who is logged in. The role CUSTOMER becomes the authority ROLE_CUSTOMER. When the request reaches the filter chain and it asks "who is this?", sam is already there. The first test has no annotation at all, so nobody is logged in.
The test that really matters: Noah opens Emma's ticket
Role checks are easy to get right. Ownership is where real leaks happen. Emma is a customer; ticket 1, "Printer is offline", is hers, so she gets 200 and the right title. Noah has the same role, CUSTOMER, but he's a different customer. He opens Emma's ticket and must get 403. The role is right, the owner is not. This test proves one customer can't read another customer's ticket, and it will fail loudly if someone ever removes that check (for example, the missing @EnableMethodSecurity from Method Security).
Run it
mvn test
Tests run: 5, Failures: 0
BUILD SUCCESS
No user gets 401, the customer gets 403, the agent and Emma get 200, and Noah gets 403. Each test asks for one answer, and gets it.
Break it: forget the role
On a scratch copy, the agent test says only @WithMockUser(username = "chaand"), with no roles:
anAgentSeesAllTickets FAILED
Status expected:<200> but was:<403>
BUILD FAILURE
Without roles, @WithMockUser gives the user the default role USER, so the granted authorities are just ROLE_USER. The rule wants ROLE_AGENT and says no. The test was right to fail: the test user wasn't who you meant. Always give the test user the role you mean.
Common mistakes
- Not importing
SecurityConfig. The slice then runs Boot's default security, and your tests check the wrong rules. - Testing only the happy path. A security test suite without a 401 and a 403 proves nothing about security.
- No ownership test. Two users with the same role is the case that leaks data.
- Leaving out
roles. You getROLE_USER, not what you intended.
Try it yourself
Add a sixth test: an agent opens Emma's ticket 1. What status do you expect, and which line of the controller's check lets the agent through?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
A RegisterForm record with three annotations checks the name, email and password at the door. Bad data goes back to the form with a message under each field; good data becomes an Account row. And the password is still stored as plain text, which the next step fixes.
Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
A guard at the gate and a hash in the table. A SecurityFilterChain lists the open pages and sends everything else to /login, a BCrypt PasswordEncoder bean hashes every password, and a UserDetailsService answers 'who is this email?' from the ACCOUNT table.
Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
Until now every login got .roles("USER") typed into the code. A Role enum on Account, one changed line in the UserDetailsService and one hasRole rule let Chaand open /admin while Emma gets a 403 and a visitor is sent to log in.
Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
One header file, three menus: a visitor sees Register and Login, Emma sees her email and Logout, Chaand also gets Admin. Then each post knows its author through @ManyToOne, and the Edit button shows only for the author or an admin.
