javaspringspring-mvcdependency-injectionsession-scope

How to retrieve a session-scoped bean inside AuthenticationSuccessHandler?


I have a custom AuthenticationSuccessHandler.

What I want to do is to set some session data within onAuthenticationSuccess method.

To store session data I want to use a session-scoped bean, which works fine within any controller.

But if I try to retrieve it within onAuthenticationSuccess method, I get an exception:

Error creating bean with name 'scopedTarget.sessionData': Scope 'session' is not active for the current thread;

My code is:

WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
SessionData sessionData = context.getBean(SessionData.class);

Any ideas?


Solution

  • You can try to declare a listener that exposes state necessary to implement session scope:

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

    By default that state is exposed by DispatcherServlet, so it's not available before request enters DispatcherServlet (e.g. in Spring Security filters).