Access RequestContextHolder and HttpServletRequest.getUserPrincipal () from AuthenticationSuccessHandler

I have a Spring-MVC application (i.e. I am using a Spring dispatcher servlet). I also use Spring Security to authenticate users. Since I am using the Spring dispatcher servlet, I should NOT declare

<listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> 

in my web.xml to be able to use RequestContextHolder (if I understand the documentation correctly).

My question relates to my implementation of the org.springframework.security.web.authentication.AuthenticationSuccessHandler interface:

 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 } } 

Could you explain why in the above code, RequestContextHolder.currentRequestAttributes() and HttpServletRequest.getUserPrincipal() do not work (they work inside the controller)?

Thanks!

+6
source share
1 answer

Spring Security is based on filters. This is why you need a RequestContextListener defined as the DispatcherServlet has not been called when the spring-security event occurs and the spring request context will not be configured.

+4
source

Source: https://habr.com/ru/post/898336/


All Articles