I'm trying to test Spring Security using @WithMockUser - the annotation actually causes a user to appear in the request, but the roles parameter seems to be ignored.
What can I do to make @WithMockUser annotations work properly with supplied roles?
Test class:
package com.kubukoz.myapp;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import javax.persistence.EntityExistsException;
import javax.transaction.Transactional;
import java.util.Arrays;
import static org.junit.Assert.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {MyApplication.class, WebSecurityConfig.class})
@WebAppConfiguration
@ActiveProfiles({"debug"})
@TestExecutionListeners(listeners = {WithSecurityContextTestExecutionListener.class})
@TransactionConfiguration(defaultRollback = true)
@Transactional(rollbackOn = Exception.class)
public class MyApplicationTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.dispatchOptions(true)
.build();
}
@Test
public void testAdmin() throws Exception{
mockMvc.perform(get("/admin/health").with(user("user").roles("ADMIN"))).andExpect(status().isOk()); //passes
}
@Test
@WithMockUser(username = "some-user@gmail.com", roles="ADMIN")
public void testAdminAgain() throws Exception {
mockMvc.perform(get("/admin/health")).andExpect(status().isOk()); //status is 403
}
}
Aucun commentaire:
Enregistrer un commentaire