具有@WithMockUser()的Spring Security MockMVC始终返回成功状态

时间:2019-10-19 09:54:10

标签: spring spring-security mocking mockmvc

我正在尝试测试某些终结点(对于测试而言是我的新手),并且遇到一个问题,即模拟身份验证似乎总是被接受并返回200。

没有Auth的测试似乎只有一个ROLE_USER的用户,但是端点仍然返回成功。

我只能假定MockMVC实例未使用我的SecurityConfig,默认值为“让所有请求都发生”吗?

即使将我的安全配置更改为仅允许具有“ ROLE_GOD”的用户,也仍会显示状态。所有测试请求都可以。

尝试过Spring Docs和此处的一些帖子,但没有任何运气...

任何帮助将不胜感激。

DataController.getIndex org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ca25360: Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER
Expected :CLIENT_ERROR
Actual   :SUCCESSFUL
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class DataControllerTest {

    @LocalServerPort
    private int port;

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void before() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext)
                .apply(springSecurity())
                .build();
    }

    @Test
    @WithMockUser(roles = {"ADMIN"}, setupBefore = TestExecutionEvent.TEST_METHOD)
    public void getRequest() throws Exception {
        System.out.println("!!!" + SecurityContextHolder.getContext().getAuthentication());
        this.mockMvc.perform(get("http://localhost:" + port)).andDo(print())
                .andExpect(status().is2xxSuccessful())
                .andExpect(content().string("HELLO!"));
    }

    @Test
    @WithMockUser(setupBefore = TestExecutionEvent.TEST_METHOD)
    public void getRequestWithoutAuth() throws Exception {
        System.out.println("!!!" + SecurityContextHolder.getContext().getAuthentication());
        this.mockMvc.perform(get("http://localhost:" + port)).andDo(print())
                .andExpect(status().is4xxClientError());
    }

}

我的SecurityConfig:

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }

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

        http.cors().disable().csrf().disable()
                .exceptionHandling()
                .and()
                .formLogin().disable()
                .authorizeRequests()
                .antMatchers("/").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    }
}

1 个答案:

答案 0 :(得分:0)

好的。 我是白痴。

我的URI在测试类MockMVC.perform()中不正确。

 @Test
    @WithMockUser(roles = {"ADMIN"}, setupBefore = TestExecutionEvent.TEST_METHOD)
    public void getRequest() throws Exception {
        System.out.println("!!!" + SecurityContextHolder.getContext().getAuthentication());
        this.mockMvc.perform(get("http://localhost:" + port+"/")).andDo(print())
                .andExpect(status().is2xxSuccessful())
                .andExpect(content().string("HELLO!"));
    }

    @Test
    @WithMockUser(setupBefore = TestExecutionEvent.TEST_METHOD)
    public void getRequestWithoutAuth() throws Exception {
        System.out.println("!!!" + SecurityContextHolder.getContext().getAuthentication());
        this.mockMvc.perform(get("http://localhost:" + port+"/")).andDo(print())
                .andExpect(status().is4xxClientError());
    }

URI需要在​​port参数后面加上/。

CORRECT : http://localhost:9999/
INCORRECT : http://localhost:9999