2014-04-28 56 views
4

我无法在我的测试中正确配置安全性。 我的网络安全性配置:用于测试的Spring Boot安装安全性

@Configuration 
@EnableWebMvcSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
       .authorizeRequests() 
       .antMatchers("/api/**").hasRole("USER") 
       .and() 
       .httpBasic() 
     ; 
    } 
} 

而我的测试类:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration 
@ContextConfiguration(classes = {Application.class, AppConfig.class, WebMvcConfig.class, WebSecurityConfig.class}) 
@WebAppConfiguration 
public class TestControllerTest { 

    @Autowired 
    private WebApplicationContext wac; 

    private MockMvc mockMvc; 

    @Before 
    public void setUp() { 
     MockitoAnnotations.initMocks(this); 
     this.mockMvc = webAppContextSetup(wac).dispatchOptions(true).build(); 
    } 

    @Test 
    public void getTest() throws Exception { 
     mockMvc 
       .perform(get("/api/test")) 
       .andExpect(status().isForbidden()) 
     ; 
    } 
} 

我得到的是不执行404个状态码意味着安全层,所以它不是在我的测试类配置正确。 我尝试将@ContextConfiguration的类切换为@SpringApplicationConfiguration,但未成功。

回答

7

进行以下修改你的代码:

@Autowired 
    private FilterChainProxy filterChainProxy; 


    @Before 
    public void setUp() { 
     MockitoAnnotations.initMocks(this); 
     this.mockMvc = webAppContextSetup(wac).dispatchOptions(true).addFilters(filterChainProxy).build(); 
    } 
+0

谢谢!它解决了我的问题 – user3168219

+0

这很好听! – geoand

+0

谢谢你的回答!我花了一整天搞清楚我在做什么错了:) – jeremija

6

正如reference说春季安全4.0.4:

为了使用Spring Security使用Spring MVC测试是必要的将Spring Security FilterChainProxy添加为Filter。还需要添加Spring Security的TestSecurityContextHolderPostProcessor以支持在Spring MVC测试中使用注释运行为用户。这可以使用Spring Security的SecurityMockMvcConfigurers.springSecurity()完成。

例子:

import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*; 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration 
@WebAppConfiguration 
public class TestControllerTest { 

    @Autowired 
    private WebApplicationContext wac; 

    private MockMvc mockMvc; 

    @Before 
    public void setup() { 
     mockMvc = MockMvcBuilders 
       .webAppContextSetup(wac) 
       .apply(springSecurity()) //will perform all of the initial setup to integrate Spring Security with Spring MVC Test 
       .build(); 
    } 
+0

请注意:这是必要的,例如, @WickMovkUser。 – sn42