tinmegali
5/8/2019 - 8:29 PM

Spring - Testing access security

The following snippets should be applied to SpringBoot since SpringMVC has a differente logic about it.

Oficial Documentation

Configuring the Test

With the follogin @annottations it will be possible to execute most of the tests, however if the intention is to test restricted access to certain method calls, using @PreAuthorize, @PostAuthorized or @Secured, other approach will be necessery.

Default stat annotation: wihout WebContext

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ClassToBeTested.class)
public class StandardUnitTest {
  // ... tests
}

Start annotation with WebContext

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ClassToBeTested.class)
@AutoConfigureMockMvc
public class StandardUnitTest {
  // ... tests
  @Autowired
    private MockMvc mvc;
}

Sample test with MockMvc

@Test
public void exampleTest() throws Exception {
  this.mvc.perform(get("/")).andExpect(status().isOk())
        .andExpect(content().string("Hello World"));

Defining the Authentication

Using default User

@Test
@Transactional
\!h @WithMockUser(username = "user", authorities = 'ROLE_USER')
public void createInstitutionWithoutProperAuthority() throws Exception {
  int databaseSizeBeforeCreate = institutionRepository.findAll().size();
  // Create the Institution
  institution = createEntityWithContact(em);
  InstitutionDTO institutionDTO = institutionMapper.toDto(institution);
  mvc.perform(post("/api/institutions")
    .contentType(TestUtil.APPLICATION_JSON_UTF8)
    .content(TestUtil.convertObjectToJsonBytes(institutionDTO)))
    // user doesn't have authority, hence the call should be forbidden
    \!h .andExpect(status().isForbidden());

  // Validate the Institution in the database
  List<Institution> institutionList = institutionRepository.findAll();
  assertThat(institutionList).hasSize(databaseSizeBeforeCreate);
}

Creating User annotation

@Retention(RetentionPolicy.RUNTIME)
@WithMockUser(username = "admin", authorities = AuthoritiesConstants.ADMIN)
public @interface WithMockAdmin {
}