Spring boot session timeout event listener - java

I want to perform a custom event when a user is logged out from a session timeout. The user is successfully logged out after exactly the length of time specified by my application.properties:
server.servlet.session.timeout=10
server.servlet.session.cookie.max-age=10
I have found a few similar solutions which involve a SessionDestroyedEvent, for example:
#Slf4j
#Component
public class SessionExpiredListener implements ApplicationListener<SessionDestroyedEvent> {
#Override
public void onApplicationEvent(SessionDestroyedEvent event) {
for (SecurityContext securityContext : event.getSecurityContexts()) {
Authentication authentication = securityContext.getAuthentication();
UserPrincipal user = (UserPrincipal) authentication.getPrincipal(); // UserPrincipal is my custom Principal class
log.debug("Session expired!" + user.getUsername());
// do custom event handling
}
}
}
The problem is the SessionDestroyedEvent is not triggered at the same time as the session timeout, in my tests it has triggered up to 5 minutes after the session has expired.
I have also tried using sessionDestroyed in HttpSessionListener but with similar results.
Is there an event that will trigger exactly when the session expires, or is there some way to achieve this?

The sessionDestroyed() method is called when the web container expires the session.
In Tomcat, session expirations happens every minute, and I think it is the case with other servlet containers.
So, even after the session times out there could be a delay until the next detection of expirations.
Session management is done by servlet container, and your application is getting notification from it.
And there is no way to be notified at the exact time of session expiration.

I also had handle the event when the user is logged out by session timeout. For me, this solution was helpfull: https://stackoverflow.com/a/18128496/4074871
Additionally I had to register the HttpSessionEventPublisher as mentioned in https://stackoverflow.com/a/24957247/4074871 because I had no web.xml for listener registration.

Related

JavaMelody and Spring Session

We use Spring-session. And we use JavaMelody for monitoring sessions.
JavaMelody uses net.bull.javamelody.SessionListener for monitoring sessions. It is implementation of HttpSessionListener from servlet API.
Spring-session have SessionEventHttpSessionListenerAdapter for capability with servlet api session listeners. It listens Spring session events and submit http session events. Wherein it creates ExpiringSessionHttpSession (wrapper for spring session).
private HttpSessionEvent createHttpSessionEvent(AbstractSessionEvent event) {
ExpiringSession session = event.getSession();
HttpSession httpSession = new ExpiringSessionHttpSession<ExpiringSession>(session,
this.context);
HttpSessionEvent httpSessionEvent = new HttpSessionEvent(httpSession);
return httpSessionEvent;
}
We use SessionEventHttpSessionListenerAdapter for working net.bull.javamelody.SessionListener. Spring sessions successful displays in JavaMelody sessions view.
But we have a problem. JavaMelody button "invalidate session" doesn't work correct. JavaMelody uses http session method invalidate for handling this button. The implementation method in ExpiringSessionHttpSession (part of Spring) looks like dummy:
public void invalidate() {
checkState();
this.invalidated = true;
}
In facts, it only set invalidate = true in adapter, but it is not invalidate session in Spring session registry. Real spring session continues be valid, and user can be used this session.
Could you have solution for this problem?
I found some solution but I don't think that it's good. We can override spring SessionEventHttpSessionListenerAdapter and ExpiringSessionHttpSession. And we can override method invalidate (adding call session registry). In this case, JavaMelody will invalidate session in registry.
Probably exists solution is better. I would be glad to get it.

How to extend or change the session timeout value i.e. session.maxAge in Play Framework (Java)

I am new to Play Framework and working on session Management. My requirement is, I need to change the session TimeOut value to certain value when user is still using the application (webpage).
Condition:
If user has been logged in, and the timeout value it 30 minutes. User is working on the same application and the session should be expired after 30 minutes of interval time. As the session timeout is 30 minutes it is expiring and sending user to login page. I want a way to handle the session so that when the user is accessing the application and session is near to end. I want to change the value to double. So that user can use same session.
This is default value I have set
###session timeout is 30 minutes (1800000 Milliseconds)
play.http.session.maxAge = 1800000
I am using below way for checking session validation in Play Framework using Java. Please find the sample code.
public class SessionValidatorAction extends Action.Simple{
public CompletionStage<Result> call(Context ctx)
{
ctx.session().get("user");
}
}
Below are the link for the same session management in Play:
https://www.playframework.com/documentation/2.6.x/JavaActionsComposition#Action-composition
Note:
I did not find any methods in session obejct like we get in java(J2EE)
Session.setMaxInactiveInterval(15*60);
Please guide me.
Thanks in advance..
Inherit the filter class and implement the apply method. So, if you call "withsession in "result:Result" as parameter of previous session, new session will be created. Of course, the expiration time will be extended again.
sorry I'm not good at English. I hope this helps.
here is my code by Scala
#Singleton
class SessionDelayFilter #Inject()(implicit override val mat: Materializer,
exec: ExecutionContext) extends Filter {
override def apply(nextFilter: RequestHeader => Future[Result])
(requestHeader: RequestHeader): Future[Result] = {
nextFilter(requestHeader).map { result =>
result.withSession(result.session(requestHeader))
}
}
}

Get security context from SessionDestroyedEvent in Spring Session

I am using Spring Session 1.0.1. I need to execute some logic when the user logs out, and I need to rely on the HTTP session being invalidated to cover the case where the user fails to explicitly log out.
The standard Spring Security SessionDestroyedEvent includes any applicable SecurityContext, but the Spring Session version of SessionDestroyedEvent only contains the session id. By the time this event fires, the session is no longer held by the SessionRepository so it can't be looked up by id.
Is there any way to retrieve the SecurityContext from the expired session using Spring Session?
Unfortunately there is not. The problem is that at the time Redis fires the event, the session is already gone. Furthermore, the event received from Redis does not contain the original information. This means there is no way to retrieve the SecurityContext.
For updates on this please track spring-projects/spring-session/issues/4
For sring-session 1.1+ with Redis
https://docs.spring.io/spring-session/docs/current/reference/html5/#httpsession-httpsessionlistener
You must configure HttpSessionEventPublisher and after that spring-session will propagate sessionDestroy event
#Configuration
#EnableRedisHttpSession
public class RedisHttpSessionConfig {
#Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
// ...
}
So you can use standard spting SessionDestroyedEvent listener
#Component
public class SessionDestroyListener implements ApplicationListener<SessionDestroyedEvent> {
#Override
public void onApplicationEvent(SessionDestroyedEvent event) {
logger.debug("session destroyed {}", event.getId());
if(!event.getSecurityContexts().isEmpty()) {
...
}
}
}

Set Liferay Hook on session timeout

I want to write a Hook in Java that is executed if the session of my Liferay 5.2.3 Portal times out.
I managed to write a Hook that is executed whenever the user clicks the logout link with the following setup in the liferay-hook.xml:
<hook>
<event>
<event-class>com.extensions.hooks.LogoutHook</event-class>
<event-type>logout.events.pre</event-type>
</event>
</hook>
However the Logout Hook does not get called if the session times out, but I need to execute the same method on a timeout. I did not find an event-type for a session timeout.
Is there a way to execute a Java-Method when the session times out and identify the User-ID of the ended session?
There is an event which will be triggered upon Session Expiry/TimeOut event of User Session,
# Servlet session destroy event
servlet.session.destroy.events = com.extensions.hooks.CustomPreSessionExpireAction
You can either add this property in liferay-hook.xml or portal.properties [Written in Hook] or portal-ext.properties.
And can be used as ,
public class CustomPreSessionExpireAction extends SessionAction {
#Override
public void run(HttpSession session) throws ActionException {
//Code
}
}
However, We can only use HttpSession here. So, you need to figure out the way to get userId here.
Thanks

Java:Why http session is not destroyed when tab or browser is closed?

I have the following implementation of HttpSessionlistener
public class SessionListener implements HttpSessionAttributeListener, HttpSessionListener {
public void attributeAdded(HttpSessionBindingEvent event) {
...
}
public void attributeRemoved(HttpSessionBindingEvent event) {
...
}
public void attributeReplaced(HttpSessionBindingEvent event) {
}
//HttpSesion creation & destruction
public void sessionCreated(HttpSessionEvent event) {
HttpSession session = event.getSession();
//log created time
}
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession session = event.getSession();
long destroyedTime = System.currentTimeMillis();
//log destroyed time
}
}
Basically i log the session creation and destruction time.
But if the session is long (default to 30 minutes), and user closes browser meanwhile, the
sessionDestroyed
is not called ?
Why is that ?
Is there a workaround to log exactly the when the session was destroyed (when user closes the browser)? Should'nt be this be the browser's problem, to kill the session when it is closed ?
Is there any interface that i have to implement for this to work ?
Thank you !
How would the server know when the browser is closed or the tab closed? At that point the browser doesn't send anything to the server.
This is a fundamental part of HTTP - it's a request/response protocol, not a "permanently open conversation" where you can tell if one party leaves the conversation. Think of it as a series of telegrams rather than a phone call - and you can't tell when you've received the last telegram you're going to get.
You'll need to design your way round this - to avoid needing to know when the browser has been closed. There are some ugly hacks to work around it - making AJAX poll the server with a heartbeat message, for example - but changing the design is a better solution.
NOTE: As jwenting commented below, this it's not 100% safe at all. If the the onunload event does not get triggered by a closing event of the browser tab or window, then this would fail.
I had the same problem, and solve it using an intrusive JavaScript event:
window.onunload
Let me briefly explain, lets say you have a JavaScript function that post, using jQuery, the current Session ID to that Servlet to invalidate it, like this:
function safeexit(){
$.post("/SessionKillServlet", { SID = <%=session.getId()%> }, function(data){});
}
To call that function, you just need to bind it like these:
window.onunload = safeexit; //without the ()
Now, safeexit method will be called when the TAB or BROWSER WINDOW gets closed (or in a redirection).
Session objects live in the server and are controlled by the server. Only the server can create or destroy sessions. So if the client is closed the session lives until it expires. The client can only suggest to the server that it can destroy some session. This request must be explicit somehow. Hence, when you close a browser window, there's no implicit request to the server informing that it must destroy a given session.
With out a lot of work the browser does not inform the server that the window is closed, therefore Java can not know when to destroy the session. Hence the time out is in place and is the first the server knows that this session can be distroyed.
You could try and play an ajax call on the javascript event document.onunload
https://developer.mozilla.org/en/DOM/window.onunload but you will need to be sure that the user is not still within your site when you do this.
If you need the session to be destroyed when a browser window/tab is closed you might attach a JavaScript handler to the onunload event that makes some sort of AJAX call to a resource that call kill the session.
Note that the onunload event does not always fire so it's not totally trustworthy. One trusty way might be to use a "heartbeat" system.
there is some hacks for knows
following code for destroy session when user closes browser
client side:
<script src="jquery path"></script>
<script>
window.onunload = function(){ $.get("${request.contextPath}/logout"); }
</script>
server side: create request mapping for "/logout"
public void doGet(HttpServletRequest request, HttpServletResponse) {
request.getSession().invalidate();
System.out.println('destroy from logout on unload browser');
}
Following code is optional
use session listener when want to know when session destroyed
// in class
import javax.servlet.*;
import javax.servlet.http.*;
public class SesListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Session created...");
}
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Session destroyed...");
}
}
//-----------------------------------------
// in web.xml
<listener>
<listener-class>SesListener</listener-class>
</listener>
As Eric mentioned the unload event on the browser can call a javascript function, which in turn can access an url through a servlet that logs you out. You need not wait for the actual response from the servlet.
The web browser interacts with the server through the http protocol and that is stateless.
you can just verify if your session user , aren't null like :
if (session.getAttribute("user") != null )
sessionsetAttribute("user","null");

Categories

Resources