2017-02-25 102 views
2

我有一個WebSecurityConfigurerAdapter的自定義實現,其中我重寫了config()方法來授權具有匹配器的請求。如何使用Spring MockMVC自定義Spring Security WebSecurityConfigurerAdapter

我需要創建單元測試,使用模擬mvc發送請求到我的控制器,以確保它們被正確阻塞。但是當我運行我的測試時,他們不會加載我的WebSecurityConfigurerAdapter實現。

重寫WebSecurityConfigurerAdapter ::配置()從我SecurityConfigSso.class方法:

@Override 
protected void configure(HttpSecurity http) throws Exception { 

    http.authorizeRequests() 
      .antMatchers("/img/**", "lib/**", "/api/event**", "/api/event/**","/login/cas**").permitAll() 
      .antMatchers(HttpMethod.GET, "/**").hasAnyAuthority(AvailableRoles.ANY) 
      .antMatchers(HttpMethod.POST, "/**").hasAnyAuthority(AvailableRoles.ADMIN, AvailableRoles.GIS_ANALYST) 
      .antMatchers(HttpMethod.PUT, "/**").hasAnyAuthority(AvailableRoles.ADMIN, AvailableRoles.GIS_ANALYST) 
      .antMatchers(HttpMethod.DELETE, "/**").hasAnyAuthority(AvailableRoles.ADMIN, AvailableRoles.GIS_ANALYST) 
      .anyRequest().authenticated(); 
} 

這是我的單元測試:

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration(classes = { SecurityConfigSso.class }) 

public class SecurityTestControllerTests { 

    private final String SECURITY_URL = "/security"; 

    private MockMvc mockMvc; 

    @Autowired 
    private WebApplicationContext context; 

    @Before 
    public void init() { 
     Assert.assertNotNull(context); 
     mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); 
    } 

    @Test 
    public void postMethodShouldBeForbiddenToGuest() throws Exception { 
     this.mockMvc.perform(post(SECURITY_URL).with(user("test").roles(AvailableRoles.GUEST))) 
      .andExpect(status().isForbidden()).andReturn(); 
    } 
} 

該測試的結果應是一個403從服務器,但它仍然是200 ... :(

回答

相關問題