Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot 1.4 testing with Security enabled?

Tags:

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?

like image 498
Lithicas Avatar asked Jun 14 '16 16:06

Lithicas


People also ask

What does @RunWith SpringRunner class mean?

@RunWith(SpringRunner. class) tells JUnit to run using Spring's testing support. SpringRunner is the new name for SpringJUnit4ClassRunner , it's just a bit easier on the eye.


2 Answers

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());
}
like image 64
Andy Wilkinson Avatar answered Sep 22 '22 01:09

Andy Wilkinson


As an alternative to the previous answer, it's possible to use the following:

@Test
public void basicAuth() throws Exception {
    this.mockMvc
            .perform(get("/")
                .with(SecurityMockMvcRequestPostProcessors.httpBasic("user", "secret"))
            )
            .andExpect(status().isOk());
}

since it will generate the same header:

Headers = [Content-Type:"...", Authorization:"Basic dXNlcjpzZWNyZXQ="]
like image 34
PavelPraulov Avatar answered Sep 21 '22 01:09

PavelPraulov