2

I'm trying to test the home controller

@RequestMapping("/")
@ResponseBody
String home() {
    return "Hello World!";
}

I'm using spring security using as username "user" and test as password by default but @PreAuthorize is not working

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@PreAuthorize("hasRole('ADMIN')")
public class HomeControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    @WithMockUser(username = "user", password = "test", roles = "ADMIN")
    public void home() throws Exception {
        String body = this.restTemplate.getForObject("/", String.class);
        assertThat(body).isEqualTo("Hello World!");
    }

}

The result

Expected result:

<"[Hello World!]">

Actual result:

<"{"timestamp":1501100448216,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/"}]">

Am I missing something?

Carlos Chávez
  • 422
  • 5
  • 14
  • 1
    You are invoking a real controller so using `@WithMockUser` is pretty much useless here. That would only work if you would directly call the `home()` method on the controller. Assuming you have basic authentication setup for login you should send the credentials with your request. Also `@PreAuthorize` on your test case won't achieve anything. – M. Deinum Jul 28 '17 at 17:45

1 Answers1

1

Try to add the following to your test class:

@TestExecutionListeners(mergeMode = MergeMode.MERGE_WITH_DEFAULTS, listeners = {
        WithSecurityContextTestExecutionListener.class
})

And the following dependency if you don't have it:

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

Spring security require an extra listener that is not present in tests by default so you need to tell spring to add it by specifing the @TestExecutionListeners annotation in merge mode so it will merge the current listed listeners with the listeners you want to add - in this case WithSecurityContextTestExecutionListener

Tom
  • 3,711
  • 2
  • 25
  • 31
  • Thanks but it didn't work i'm receiving the same result :/ – Carlos Chávez Jul 27 '17 at 20:02
  • Try also to add `ROLE_ADMIN` to the `roles` in `@WithMockUser`. Spring security by default check for the prefix `ROLE` (but in `@PreAuthorize` keep it as `ADMIN`) – Tom Jul 28 '17 at 06:31