Spring: Invoking a method before session timeout - spring

I currently have a Spring 3 project and what I want to do is retrieve my session when the session expires. I have been doing some research and apparently the HttpSessionBindingListener can handle this although in a Spring project, I can't seem to figure out how to implement this properly. Within my session, I save a UserDetailsImpl object which contains my User object. Should I be implementing the HttpSessionBindingListener on the stated objects?
To be clear, what I want to do is retrieve the user's id from the session object before it expires.
EDIT: Apparently the HttpSessionBindingListener does not work properly in Websphere but it is okay in Tomcat. Are there any other alternatives?

You can also register listener in web.xml:
<listener>
<listener-class>com.example.MyHttpSessionListener</listener-class>
</listener>
And use method sessionDestroyed()
This is detailed describd in this answer: https://stackoverflow.com/a/3720512/516167
Inject Spring Application Context in this Listener like is described in this question:
How to inject dependencies into HttpSessionListener, using Spring?
Other possible solution are described here:
Logout/Session timeout catching with spring security

Related

Spring Security 4 sessionRegistry doesn't populate Principal list

I am trying to implement a function where a admin user can terminate another user's session. I followed the official Spring Security documentation here: http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#list-authenticated-principals and started with getting all currently logged in users through sessionRegistry.getAllPrincipals(), but it always returned an empty list.
I set a breakpoint in SessionRegistryImpl.registerNewSession() and could see it did indeed get invoked and it did add the UserDetails (my own implementation with both equals() and hashCode() implemented) to the hashmap principals. But when I access sessionRegistry bean from a Spring MVC controller, the list is always empty.
My configuration looks pretty much the same as the documentation.
How to fix this? Did anyone successfully get SessionRegistry to work with Spring Security 4? I remember I made it work with Spring Security 3 by following these intructions(enter link description here)
OK, so I fixed the issue by cleaning up the Spring configuration files, as suggested by the comments. Someone messed up with the web.xml - he added a reference to the context XML that is already referenced by the Spring's DispatcherServlet, causing it to be loaded twice. He didn't know it, because Spring references the file implicitly.
P.S.
I learned my lessons, but 2 things the Spring folks could do better (maybe in Spring 5?):
There shouldn't be implicit context file loading. Currently, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application's WebContent/WEB-INF directory. Convention over configuration fails in this case.
There should be warning when a bean is loaded twice, if someone need to override a bean definition, he must declare explicitly. Otherwise it would take a lot of time to debug the kind of error this mistake will cause.

Capture Spring Session Destroy Event without registering the HttpSessionEventPublisher Listener

I wanted to perform some clean-up activity during Spring Session destroy (logout and timeout) and tried following the solution provided at this thread
but what made me curious is that, my application is a Spring Boot application and I didn't have to register the HttpSessionEventPublisher Listener , i just implemented the ApplicationListener interface and used the onApplicationEvent() method to capture the SessionDestroyEvent.
My question is, How did my code work without registering this listener
?
here is the answer from the Spring Session documentation itself
http://docs.spring.io/spring-session/docs/current/reference/html5/#api-redisoperationssessionrepository-sessiondestroyedevent
If you are using #EnableRedisHttpSession the SessionMessageListener and enabling the necessary Redis Keyspace events is done automatically. <<

Authentication object not found thrown by DispatcherServlet before #Preauthorize spring security annotation is applied

When i am trying to use #PreAuthorize("#accessControl.hasActivity('abc')") on spring controller method i am getting Authentication object was not found in security context.
After debugging found that DispactcherServlet is throwing this exception.
i have set SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_THREADLOCAL);
when i first create Authentication object and set in security context
Also tried with SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL); but no luck still it does not work.
I am not able to understand why spring is servlet is throwing this exception
First, doing authentication in a Spring MVC interceptor is odd. Consider using a filter before DispatcherServlet. There is a lot of documented examples.
Secondly, SecurityContextHolder.setStrategyName re-initializes the strategy and possibly makes all previously authentications inaccessible so you must only call it once (if any time), before any authentication is made.
Thirdly, if you want to set the current authentication to be used by #PreAuthorize and are sure what you are doing, use SecurityContextHolder.getContext().setAuthentication(anAuthentication);. In most cases, there is a suitable filter in the API that already does this for you.

Hibernate.Initialize(x.getXX) with Spring and Junit

I use to hibernate before and I require an opensession to use Hibernate.Initialize()
but apparently for Spring, if OpenSessionInViewInterceptor is set up properly, it can use Hibernate.Initialize() anywhere.
My question is, what must I setup to use Hibernate.Initialize() in JUnit?
The whole point of OpenSessionInViewInterceptor is precisely to leave the Hibernate session open until the view has been rendered. This is why you can call Hibernate.initialize() "anywhere": Spring doesn't close the session until the request has been completely handled by the view.
So the answer is always the same: to be able to call this method, the session must be opened.

spring-security-redirect is not read by spring security 3.1?

So we're using spring-security-redirect as a parameter in the form that is sent to j_spring_security_check, in order to send the user to the correct page after a successful login. Migrating from Spring security 3.0 to 3.1, this stopped working. We use a subclass of SavedRequestAwareAuthenticationSuccessHandler, overriding onAuthenticationSuccess(), and debugging that method I see that getTargetUrlParameter() returns null. isAlwaysUseDefaultTargetUrl() returns false.
Browsing around I can't find anyone having similar problems... I find some references to AbstractAuthenticationTargetUrlRequestHandler.DEFAULT_TARGET_PARAMETER, which seems to have disappeared in 3.1.
Any ideas?
As per Spring security 3.1 xsd,
Attribute : authentication-success-handler-ref
Reference to an AuthenticationSuccessHandler bean which should be used to handle a successful authentication
request. Should not be used in combination with default-target-url (or always-use-default-target-url) as the
implementation should always deal with navigation to the subsequent destination.
So, in your subclass, you have to perform the redirection.

Resources