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

标签 spring authentication spring-mvc spring-security

我有一个 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/

相关文章:

XMLBeanDefinitionStoreException : Cannot find the declaration of element 'beans'

spring - 如何在 Quartz Job 中使用 @Autowired?

ruby-on-rails - 在生产应用程序中从头开始进行身份验证?

java - GSS-API Java 奇怪的错误

java - 限制ip地址访问web服务

java - 集成 springMVC 和 extjs

java - 失败步骤的 Spring 批处理作业退出状态

java - Spring 缓存 : Evict multiple caches

authentication - SonarQube 6.7 使用 Sonar Auth Github 1.3 插件

java - SDK支持diff spring版本