我正在尝试为具有弹簧安全性的实践项目编写一些测试,并且正在使用MockMvc和相关类来实现。
所以我的基本配置如下:
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
具有与此类似的测试:
@Test
public void handleUserJSONRequest_shouldReturn401_withoutLoggedInUser() throws Exception{
ResultActions action = mvc.perform(get("/userAsJSON"));
int status = action.andReturn().getResponse().getStatus();
assertTrue("expected status code = 401 ; current status code = " + status, status == 401);
}
我仍然无法实现的是编写测试以验证我的自定义会话超时是否正常工作。
我尝试了以下操作:
@Test
public void sessionTimeoutShouldInvalidateSession_withLoggedInUser() throws Exception{
ResultActions action = mvc.perform(get("/userAsJSON").with(user("user")));
MockHttpSession session = (MockHttpSession) action.andReturn().getRequest().getSession();
TimeUnit.SECONDS.sleep(20);
ResultActions action2 = mvc.perform(get("/userAsJSON").session(session));
int status2 = action2.andReturn().getResponse().getStatus();
assertTrue("expected status code = 401 ; current status code = " + status2, status2 == 401);
}
但是它仍然会返回200(出于测试目的,会话超时设置为10,并且可以通过curl验证其工作正常);所以我认为这与MockMvc和MockHttpSession的工作方式有关。
有没有办法我仍然可以测试会话超时功能?
编辑:根据要求->我的配置:
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.sessionManagement()
//number of concurrent sessions allowed for the same user
.maximumSessions(1)
.and()
.sessionFixation()
.migrateSession();
http.addFilterBefore(authenticationFilter(), BasicAuthenticationFilter.class)
.csrf().disable()
.httpBasic().disable()
.exceptionHandling()
.authenticationEntryPoint(myRestAuthenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/secured")
.hasRole("ADMIN")
.antMatchers("/userAsJSON")
.authenticated()
.antMatchers("/unsecured")
.permitAll()
.antMatchers("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(this::handleLogoutSuccess)
.invalidateHttpSession(true);
}
具有:
public void handleLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
response.setStatus(HttpServletResponse.SC_OK);
}
和:
@Component
public class MyRestAuthenticationEntryPoint
implements AuthenticationEntryPoint {
@Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" );
}
}