spring – 从AuthenticationSuccessHandler访问RequestContextHolder和HttpServletRequest.getUserPrincipal()

我有一个Spring-MVC应用程序(即我使用的是Spring的调度程序servlet).我也使用Spring Security来验证用户身份.因为我使用Spring的调度程序servlet,所以我不必声明

  

在我的web.xml中,以便能够使用RequestContextHolder(如果我正确理解文档).

我的问题涉及我的接口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安全性基于过滤器.这就是为什么你需要定义RequestContextListener的原因,因为当spring-security的内容发生并且没有设置spring请求上下文时,还不会调用DispatcherServlet.

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...