Spring 带有 @WithMockUser() 的安全 MockMVC 总是 returns 成功状态
Spring Security MockMVC with @WithMockUser() always returns Successful status
我正在尝试测试一些端点(我对测试还很陌生)并且遇到一个问题,模拟身份验证似乎总是被接受并且 returns 200。
没有 Auth 的测试似乎只有一个 ROLE_USER 的用户,但端点仍然 returns 成功。
我只能假设我的 SecurityConfig 没有被 MockMVC 实例使用,默认的 "let all requests happen" 是?
即使将我的安全配置更改为仅允许具有 "ROLE_GOD" 的用户仍然会导致所有测试请求的 status.OK。
尝试按照 Spring 文档和此处的一些帖子进行操作,但没有任何运气...
如有任何帮助,我们将不胜感激。
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);
}
}
好的。
我是个白痴。
我的 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
我正在尝试测试一些端点(我对测试还很陌生)并且遇到一个问题,模拟身份验证似乎总是被接受并且 returns 200。
没有 Auth 的测试似乎只有一个 ROLE_USER 的用户,但端点仍然 returns 成功。
我只能假设我的 SecurityConfig 没有被 MockMVC 实例使用,默认的 "let all requests happen" 是?
即使将我的安全配置更改为仅允许具有 "ROLE_GOD" 的用户仍然会导致所有测试请求的 status.OK。
尝试按照 Spring 文档和此处的一些帖子进行操作,但没有任何运气...
如有任何帮助,我们将不胜感激。
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);
}
}
好的。 我是个白痴。
我的 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