Boris
Boris

Reputation: 836

Spring Boot - @PreAuthorize does not work in test

I have controller like this

@RestController
@RequestMapping(value="/test")
@PreAuthorize("hasRole('ADMIN')")
public class TestController
{

    @RequestMapping( method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> test ()
    {

        return ResponseEntity.ok("test");
    }

}

I tried to write unit test that will test permissions to access this controllers method.

This is my test

@RunWith(SpringRunner.class)
@ContextConfiguration
 @WebMvcTest(value = TestController.class)
public class AUnitTest
{

    @Autowired
    private MockMvc mockMvc;

    private final String url = "/test";

    @Test
    @WithMockUser(roles="ADMIN")
    public void testAdminUser() throws Exception
    {
        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(this.url );
        MvcResult result = mockMvc.perform(requestBuilder).andReturn();
        assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
    }

}

When I remove roles from @WithMockUser and leave empty, by default it will have role USER and then test passes. When I put roles USER and ADMIN, it will also pass because of USER role. But whenever I set role to ADMIN it will fail, even though I set that user needs to have ADMIN role to access controller.

I tried with setting username, password, everything from Spring Security Docs, etc.

Am I missing something?

Upvotes: 8

Views: 11860

Answers (1)

Roman N
Roman N

Reputation: 5110

Try to add @EnableGlobalMethodSecurity(prePostEnabled = true) to test class.

Or add config sth like that:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class Config {
    ...
}

Upvotes: 16

Related Questions