I need to configure a maximum duration of an application session in Tomcat to 24 hours.
I was not able to find the appropriate configuration in the documentation:
https://tomcat.apache.org/tomcat-8.5-doc/config/http.html
(There is sessionTimeout
for SSLHostConfig
but I need the Connector
configuration; We terminate the SSL connection in the WebServer before Tomcat but the session management handled by Tomcat.)
Added
We already handled the session expiration timeout (Tomcat Session Timeout web.xml).
The maximum duration timeout means that even the user active during all time its application session will be invalidated after the maximum duration timeout.
HttpSessionListener
will only notify session creation and destruction but won't be invoked on each page request.
I'd implement a filter to check on session creation time and invalidate the session plus set headers or redirect.
In web.xml add:
<filter>
<filter-name>Max Session Duration</filter-name>
<filter-class>com.your.package.MaxSessionDurationFilter</filter-class>
<init-param>
<!-- Maximum session duration in hours -->
<param-name>maxduration</param-name>
<param-value>24</param-value>
</init-param>
</filter>
and a mapping like
<filter-mapping>
<filter-name>Max Session Duration</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
Then the filter implementation is like:
package com.your.package;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MaxSessionDurationFilter implements Filter {
private final long oneHourMillis = 1000*60*60;
private long maxDuration;
private FilterConfig filterConfig;
@Override
public void init(FilterConfig fc) throws ServletException {
filterConfig = fc;
maxDuration = Long.parseLong(filterConfig.getInitParameter("maxduration"));
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) req;
HttpServletResponse httpResp = (HttpServletResponse) resp;
final long creationTime = httpReq.getSession().getCreationTime();
final long currentTime = System.currentTimeMillis();
if (currentTime-creationTime > maxDuration*oneHourMillis) {
httpReq.getSession().invalidate();
// Could also set headers to 403 forbidden
// httpResp.setStatus(HttpServletResponse.SC_FORBIDDEN);
httpResp.sendRedirect("expiredsession.jsp");
} else {
chain.doFilter(req, resp);
}
}
@Override
public void destroy() { }
}