我有一个 Spring-MVC 应用程序(即我正在使用 Spring 的调度程序 servlet)。我还使用 Spring Security 来验证用户身份。由于我使用 Spring 的调度程序 servlet,因此我不必声明
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
在我的 web.xml 中,以便能够使用 RequestContextHolder
(如果我正确理解文档)。
我的问题涉及我的接口(interface)org.springframework.security.web.authentication.AuthenticationSuccessHandler
的实现:
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
int timeout = 60*60;
//does work
request.getSession().setMaxInactiveInterval(timeout); //60 minutes
System.out.println("Session timeout of user: " + authentication.getName() + " has been set to: " + timeout + " seconds.");
/*
//does not work
session().setMaxInactiveInterval(timeout); //60 minutes
System.out.println("Session timeout of user: " + request.getUserPrincipal().getName() + " has been set to: " + timeout + " seconds.");
*/
//now restore the default work flow (SavedRequestAwareAuthenticationSuccessHandler is the default AuthenticationSuccessHandler that Spring uses,
// see: http://static.springsource.org/spring-security/site/docs/3.0.x/reference/core-web-filters.html#form-login-flow-handling )
(new SavedRequestAwareAuthenticationSuccessHandler()).onAuthenticationSuccess(request, response, authentication);
}
public static HttpSession session() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return attr.getRequest().getSession(true); // true == allow create
}
}
您能解释一下为什么在上述代码中,RequestContextHolder.currentRequestAttributes()
和 HttpServletRequest.getUserPrincipal()
不起作用(它们在 Controller 内工作)?
谢谢!
最佳答案
Spring security 是基于过滤器的。这就是为什么您需要定义 RequestContextListener,因为当 spring-security 事件发生并且 spring 请求上下文尚未设置时,DispatcherServlet 还不会被调用。
关于spring - 从 AuthenticationSuccessHandler 访问 RequestContextHolder 和 HttpServletRequest.getUserPrincipal(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7605285/