Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

java - Spring Boot setup security for testing

I'm unable to configure correctly the security in my tests. My web security configuration:

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

And my test class:

@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())
        ;
    }
}

I get a 404 status code meaning the security layer is not executed, so it is not configured correctly in my test class. I tried to switch the classes from @ContextConfiguration to @SpringApplicationConfiguration without success.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Make the following modifications to your code:

   @Autowired
   private FilterChainProxy filterChainProxy;


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...