Q:

Spring - Best way to control session creation

I am currently retrieving the session timeout from a database since it should be configurable so I just can't declare it in the web.xml.
In my HttpSessionEventPublisher, I basically retrieve the session object from the HttpSessionEvent and I set the session timeout value that I've retrieved from the database using setMaxInactiveInterval.
Upon investigation, whenever I access a POST url in my site, the HttpSessionEventPublisher is triggered and it creates a new Session object. I would like to control this behavior by only creating a Session object if and only if the user is successfully authenticated (logged in, passing through the AuthenticationProvider)
Is this possible?

A:

The HttpSessionEventPublisher does not create sessions itself. It just translates servlet session events to the equivalent ones of spring security. Actually the creation of sessions is not controlled by spring security, but it can initiate one if needed. 
If you just want to set the session timeout only upon authentication, then you may extend the authentication handler you use and set the timeout there.
For example the following code extends SavedRequestAwareAuthenticationSuccessHandler and retrieves the timeout from application properties (instead of database as in your case)

@Component
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Value("#{appProperties['session.timeout']}")
    private int sessionTimeout;

    private final Logger logger = LoggerFactory.getLogger(AuthenticationSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication authentication) throws ServletException, IOException {

        logger.debug("onAuthenticationSuccess");

        HttpSession session = req.getSession();
        session.setMaxInactiveInterval(sessionTimeout);

        super.onAuthenticationSuccess(req, res, authentication);
    }
}

