Back to Research
Authorization
RBAC
Spring Security
Testing
Spring Boot
Java

How to test permissions in Spring Security (and catch the 403 before your customer)

Authorization tests in Spring Boot with @WithMockUser, MockMvc, and jwt(): 401, 403, permissions, tenant isolation, and a matrix that covers every endpoint.

8 min read

Authorization code works the day it is written and breaks silently later. Permission tests are cheap and catch it in the build. For every rule, test both sides: who may passes, who may not gets 403.

Dependency

<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-test</artifactId>
  <scope>test</scope>
</dependency>

1. @PreAuthorize in the service

@SpringBootTest
class PedidoServiceSecurityTest {

  @Autowired PedidoService service;

  @Test
  @WithMockUser(authorities = "pedidos:aprovar")
  void comPermissaoAprova() {
    assertDoesNotThrow(() -> service.aprovar(1L));
  }

  @Test
  @WithMockUser(authorities = "pedidos:ler")
  void semPermissaoRecebeAccessDenied() {
    assertThrows(AccessDeniedException.class, () -> service.aprovar(1L));
  }

  @Test
  void semUsuarioNaoPassa() {
    assertThrows(AuthenticationCredentialsNotFoundException.class, () -> service.aprovar(1L));
  }
}

2. Endpoints with MockMvc and JWT

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(PedidoController.class)
@Import(SecurityConfig.class)
class PedidoControllerSecurityTest {

  @Autowired MockMvc mvc;
  @MockitoBean PedidoService service;

  @Test
  void semTokenEh401() throws Exception {
    mvc.perform(get("/api/pedidos/1"))
       .andExpect(status().isUnauthorized());
  }

  @Test
  void semPermissaoEh403() throws Exception {
    mvc.perform(post("/api/pedidos/1/aprovar")
           .with(jwt().authorities(new SimpleGrantedAuthority("pedidos:ler"))))
       .andExpect(status().isForbidden());
  }

  @Test
  void comPermissaoEh200() throws Exception {
    mvc.perform(post("/api/pedidos/1/aprovar")
           .with(jwt().authorities(new SimpleGrantedAuthority("pedidos:aprovar"))))
       .andExpect(status().isOk());
  }
}

Import your SecurityConfig, or @WebMvcTest uses the default one. @MockitoBean replaces @MockBean since Spring Boot 3.4.

3. Tenant isolation

@Test
void tokenDeOutroClienteEh403() throws Exception {
  mvc.perform(get("/api/tenants/beta/pedidos/1")
         .with(jwt()
             .jwt(token -> token.claim("tenant_id", "acme"))
             .authorities(new SimpleGrantedAuthority("pedidos:ler"))))
     .andExpect(status().isForbidden());
}

4. A permission matrix

@ParameterizedTest(name = "{0} {1} com [{2}] -> {3}")
@CsvSource({
    "GET,  /api/pedidos/1,          pedidos:ler,     200",
    "GET,  /api/pedidos/1,          '',              403",
    "POST, /api/pedidos/1/aprovar,  pedidos:ler,     403",
    "POST, /api/pedidos/1/aprovar,  pedidos:aprovar, 200",
})
void matriz(String metodo, String url, String permissao, int esperado) throws Exception {
  var jwt = permissao.isBlank()
      ? jwt()
      : jwt().authorities(new SimpleGrantedAuthority(permissao));
  mvc.perform(request(HttpMethod.valueOf(metodo), url).with(jwt))
     .andExpect(status().is(esperado));
}

Pitfalls

  • Without @EnableMethodSecurity, annotations are ignored; the 403 test catches it.
  • Self-invocation skips the Spring proxy.
  • Test role inheritance if you use RoleHierarchy.

Related articles