4

I want to add object to HttpSession after successful user authentication. Please don't suggest solution with SavedRequestAwareAuthenticationSuccessHandler because in this app for some reason application are ingnoring original request.

public class AuthenticationSuccessListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
    @Override
    public void onApplicationEvent(InteractiveAuthenticationSuccessEvent e) {
        //adding object to HttpSession
    }
} 
winnfield
  • 273
  • 4
  • 19

1 Answers1

10

As far as I am aware, ApplicationListener instances are just beans within your ApplicationContext. Therefore you should be able to inject other beans or resources into them.

So to get a reference to the current HttpSession instance:

public class AuthenticationSuccessListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {

@Autowired
private HttpSession httpSession;

        @Override
        public void onApplicationEvent(InteractiveAuthenticationSuccessEvent e) {
               //adding object to HttpSession
        }
}

Spring will inject the HttpSession using its scoped proxy mechanism ensuring that you get the HTTPSession relevant to the current thread of execution.

You'll also need to ensure that you register a RequestContextListener in your web.xml so that Spring can inject the current HTTPSession.

<listener>  
   <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>  
</listener>
Rob Lockwood-Blake
  • 4,688
  • 24
  • 22
  • Thanks @Rob. Unfortunately I'm getting `IllegalStateException`: `java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread?` – winnfield Nov 05 '13 at 18:09
  • I've updated my answer to include the registration of the RequestContextListener that should solve your problems. – Rob Lockwood-Blake Nov 05 '13 at 18:21
  • I've already tested another solution. Instead of using RequestContextListener you can also change scope by adding @Scope("request") or editing bean attribute. – winnfield Nov 05 '13 at 20:19
  • 4
    Surprisingly, none of the above works, still getting "No thread-bound". No other ideas? Thanks – siebmanb Feb 26 '15 at 10:35
  • But seems AuthenticationSuccessListener is singleton, and seems httpSession could cause misbehaviour in multy user enviroment. – Oleksandr_DJ Oct 29 '17 at 21:59