Created
June 17, 2017 18:51
-
-
Save prasann/0dd68a2e918804d25e31298b382c4938 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.security.authentication.CredentialsExpiredException; | |
import javax.servlet.*; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpSession; | |
import java.io.IOException; | |
public class SessionExpiryFilter implements Filter { | |
private final int maxSessionLifeInMinutes; | |
private static final String SESSION_EXPIRED = "SESSION_EXPIRED"; | |
public SessionExpiryFilter(int maxSessionLifeInMinutes) { | |
this.maxSessionLifeInMinutes = maxSessionLifeInMinutes; | |
} | |
@Override | |
public void init(FilterConfig filterConfig) throws ServletException { | |
} | |
@Override | |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) | |
throws IOException, ServletException { | |
HttpServletRequest httpServletRequest = (HttpServletRequest) request; | |
HttpSession session = httpServletRequest.getSession(false); | |
String sessionId = ((HttpServletRequest) request).getRequestedSessionId(); | |
if (session == null && sessionId != null) { | |
throw new CredentialsExpiredException(SESSION_EXPIRED); | |
} | |
if (session != null && hasExceededMaximumLife(session)) { | |
session.invalidate(); | |
throw new CredentialsExpiredException(SESSION_EXPIRED); | |
} | |
chain.doFilter(request, response); | |
} | |
private boolean hasExceededMaximumLife(HttpSession session) { | |
long sessionStartTimestamp = session.getCreationTime(); | |
long currentTimeStamp = System.currentTimeMillis(); | |
return (currentTimeStamp - sessionStartTimestamp) > minutesToMillis(maxSessionLifeInMinutes); | |
} | |
private int minutesToMillis(int timeInMinutes) { | |
return timeInMinutes * 60 * 1000; | |
} | |
@Override | |
public void destroy() { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment