【问题标题】:Spring Security MockMVC with @WithMockUser() always returns Successful status带有 @WithMockUser() 的 Spring Security MockMVC 始终返回成功状态
【发布时间】:2019-10-19 09:54:10
【问题描述】:

我正在尝试测试一些端点(我对测试很陌生)并且遇到了一个问题,即模拟身份验证似乎总是被接受并返回 200。

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

我只能假设我的 SecurityConfig 没有被 MockMVC 实例使用,并且默认的“让所有请求发生”是?

即使将我的安全配置更改为仅允许具有“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());
    }

}

我的安全配置:

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

    }
}

【问题讨论】:

    标签: spring spring-security mocking mockmvc


    【解决方案1】:

    好的。 我是个白痴。

    我的 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 需要 / 跟在端口参数之后。

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

    【讨论】:

      猜你喜欢
      • 2015-02-13
      • 2019-03-07
      • 1970-01-01
      • 2015-07-14
      • 2011-05-07
      • 2019-11-02
      • 1970-01-01
      • 2021-11-09
      • 2023-04-01
      相关资源
      最近更新 更多