Spring Boot 1.4 testing with Security enabled?

Lithicas picture Lithicas · Jun 14, 2016 · Viewed 18.4k times · Source

I'm wondering how I should go about authenticating a user for my tests? As it stands now all tests I will write will fail because the endpoints require authorization.

Test code:

@RunWith(SpringRunner.class)
@WebMvcTest(value = PostController.class)
public class PostControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private PostService postService;

    @Test
    public void testHome() throws Exception {
        this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("posts"));
    }


}

One solution I found is to disable it by setting secure to false in @WebMvcTest. But that's not what I'm trying to do.

Any ideas?

Answer

Andy Wilkinson picture Andy Wilkinson · Jun 14, 2016

Spring Security provides a @WithMockUser annotation that can be used to indicate that a test should be run as a particular user:

@Test
@WithMockUser(username = "test", password = "test", roles = "USER")
public void withMockUser() throws Exception {
    this.mockMvc.perform(get("/")).andExpect(status().isOk());
}

Alternatively, if you're using basic authentication, you could send the required Authorization header:

@Test
public void basicAuth() throws Exception {
    this.mockMvc
            .perform(get("/").header(HttpHeaders.AUTHORIZATION,
                    "Basic " + Base64Utils.encodeToString("user:secret".getBytes())))
            .andExpect(status().isOk());
}