Refresh session time when user confirm's to stay online - java

I am working on JSF framework. In Web.xml session time out time is 5 min. After 4 min i am showing confirm dialog for the user whether to stay active or not. After clicking on Yes I tried sessionObject.setMaxInactiveInterval(5). But session gets invalidated after 5th min. Is there a way to extend user session time dynamically without changing time in web.xml.
public void refreshSession(){
//code to refresh the session
System.out.println("want to stay alive");
HttpSession currentSession = ServerUtility.getSession();
currentSession.setMaxInactiveInterval(2*60);
}

Web.xml sets timeout setting is global, it's applicable for the whole application.
But if you want to extend the session time, you need to create method containing following code:
HttpSession session = request.getSession();
session.setMaxInactiveInterval(5*60);
What you can do is create an endpoint which executes above-mentioned code
public void extendSession(){
HttpSession session = request.getSession();
session.setMaxInactiveInterval(5*60);
}
If User doesn't want to continue then below code will end session immediately:
session.setMaxInactiveInterval(0); // inactive immediately

Related

Spring boot session timeout event listener

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.

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))
}
}
}

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

check if session is valid or not in servlet

/****NOTE****/
in WEB.XML file I am setting session timeout property,
so may be session is expired.
/************/
I am using HttpSession object to manage session
HttpSesion session = myPersonalMethodThatReturnHttpSessionObject();
//I am using Eclipse and it provide me following details in Debug view I put Image Below
//so how can i get value of isValid field or method so here i can put in if condition
if(session != null)
{
//removing attributes from session
}
/*************************************More Description*******************************************/
My Problem is...
note1 --> session timeout is 30 min.
Step1 some one login my web apllication
Step2 session is created.
Step3 if user close web application without signout
Step4 all session attribute is there
Step5 if another user try to login.
Step6 I try to remove all session attribute and store new attribute value.
Step7 Above functionality work properly but, while session is invalidate can't remove session attribute so i need to put condition in if session is valid that remove attribute else do nothing so I need to check session is valod or not.
Since you are seeing isValid=false , I guess your session has become invalid/timedout.
You should be calling HttpSession session = request.getSession(true); or HttpSession session = request.getSession(); to always get the valid session.
The method request.getSession(true) will ensure that it will create a new session if the current session is invalid. If the current session is valid, it will return the same.
The method request.getSession(); by default calls request.getSession(true);.
Based on your update, your login process should be as follows:
HttpSession session = request.getSession(false); // returns null if no session or session is invalid
if(session != null) {
// you have old session
session.invalidate(); // invalidate session - this will remove any old attrs hold in the session
}
// create new session
session = request.getSession(); // creates new empty session
....
You cannot get the isValid field directly. The request.getSession(false) is using it and will return null, if current session is invalid. If session is already invalid you don't have to remove attributes, since they already have been removed and session is inaccessible any more.
you should create an concrete class which implement javax.servlet.http.HttpSessionListener and add your code into its two callback methods:
public interface HttpSessionListener extends java.util.EventListener {
void sessionCreated(javax.servlet.http.HttpSessionEvent httpSessionEvent);
void sessionDestroyed(javax.servlet.http.HttpSessionEvent httpSessionEvent);
}
remember to register your listener in web.xml!
You create session with HttpServletRequest object as follows.
HttpSession session = httpServletRequest.getSession();
This will give you new session if one is not already created or return existing session object.
somewhere in you method myPersonalMethodThatReturnHttpSessionObject() add the following line
HttpSession session = request.getSession(false);
This will help you to find valid session.

Can't get the session in java servlet

I am using servlets for the first time but I made a lot of progress. My servlets are working well. So I decided to put an authentication mechanism, which creates a session, if users give the right password and id's. But sessions are totally new for me. So I don't quite follow the logic but I have started to understand.
As I mentioned before one of my servlets is dedicated for logging in. If password is correct a session is created (I don't store any object/data in sessions) and client (remoteUser) is notified that the password is accepted and session is created. What client does is to reach any other servlet in the same application. Other servlets get the session to check if it is created and valid (not timed out). For that purpose in those other servlets I get the session with:
HttpSession session = req.getSession(false); //false because this is not the place to create a session. sessions should only be created in the login servlet.
But this returns a null. So I have tried:
HttpSession session = req.getSession();
And checked with session.isNew(); and I it was a new session. So the session I have created in login servlet can't be called with req.getSession(); in another servlet.
PS: When session is created in login servlet: session.setMaxInactiveInterval(300); //5 minutes
Thanks a lot for any response!
When using Google App Engine, you have to specifically enable session support. See http://code.google.com/appengine/docs/java/config/appconfig.html#Enabling_Sessions.

Categories

Resources