【发布时间】:2018-01-14 16:06:39
【问题描述】:
我正在尝试使用以下代码模拟发布请求。
我正在测试一个 Spring Security 登录请求。
MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).addFilter(springSecurityFilterChain)
.apply(springSecurity())
.build();
MvcResult mvcResult = mvc.perform(post("/j_spring_security_check?api=true").param("userName", USERNAME)
.param("password", PASSWORD)).andReturn();
代码工作正常,成功登录后,我正在重定向到另一个控制器。
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException,
ServletException {
RequestDispatcher rd = request.getRequestDispatcher("/myURL");
rd.forward(request, response);
}
当我运行测试时,我得到以下日志。重定向没有发生,映射到 /myURL 的控制器没有被调用。
11:59:55.839 [main] DEBUG o.s.mock.web.MockRequestDispatcher - MockRequestDispatcher: forwarding to [/myURL]
11:59:55.841 [main] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - The HttpSession is currently null, and the HttpSessionSecurityContextRepository is prohibited from creating an HttpSession (because the allowSessionCreation property is false) - SecurityContext thus not stored for next request
11:59:55.841 [main] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
没有报告错误。
我错过了什么吗?使用 MockMvc 时不会发生重定向吗?
【问题讨论】:
-
如何构建 MockMvc 实例?哪个版本的 Spring Security?
-
用相关细节更新了问题。我正在使用 Spring Security 4.1.2
标签: spring-mvc spring-security spring-test spring-test-mvc