【发布时间】:2018-05-01 20:23:47
【问题描述】:
我想在此处显示的示例中添加几个测试:
https://spring.io/guides/gs/securing-web/
能够验证用户在会话关闭或到期时无法再访问需要身份验证的资源。我想在我的测试中模拟以下两种情况:
a) 用户自愿结束会话(例如关闭浏览器);
b) 会话超时;
我不知道如何使用 MockMvc 重现这些情况。
我设法做到了以下几点:
@Test
public void sessionIsInvalid() throws Exception {
FormLoginRequestBuilder login = formLogin()
.user("user")
.password("password");
mockMvc.perform(login)
.andExpect(authenticated())
.andDo(mvcResult -> {
MockHttpSession session = (MockHttpSession)mvcResult.getRequest().getSession();
session.invalidate();
mockMvc.perform(get("/hello")
.session(session))
.andExpect(status().isFound());
});
}
...这似乎可行,但我不完全确定 invalidate 在这种情况下的作用以及它是否符合上述条件 a)。
为了模拟会话超时,我已经这样做了:
@Test
public void sessionExpires() throws Exception {
FormLoginRequestBuilder login = formLogin()
.user("user")
.password("password");
mockMvc.perform(login)
.andExpect(authenticated())
.andDo(mvcResult -> {
MockHttpSession session = (MockHttpSession)mvcResult.getRequest().getSession();
session.setMaxInactiveInterval(1);
Thread.sleep(3);
mockMvc.perform(get("/hello")
.session(session))
.andExpect(status().isFound());
});
}
...但这不起作用。有人可以帮我理解我做错了什么吗?
【问题讨论】:
标签: spring session spring-boot spring-test mockmvc