This is what we do at amplafi.com
(h/t See http://randomcoder.com/articles/jsessionid-considered-harmful )
in the web.xml:
<filter>
<filter-name>DisableSessionIdsInUrlFilter</filter-name>
<filter-class>
com.amplafi.web.servlet.DisableSessionIdsInUrlFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>DisableSessionIdsInUrlFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
And this java code:
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;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
/**
* remove any session id from the Url.
*
*
* Ideally we would like to only remove this container-provided functionality
* only for public portions of the web site (that can be crawled by google)
* or for links that are to be bookmarked.
*
* @author Patrick Moore
*/
public class DisableSessionIdsInUrlFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
chain.doFilter(request, response);
return;
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
/*
* Next, let's invalidate any sessions that are backed by a URL-encoded
* session id. This prevents an attacker from generating a valid link.
* Just because we won't be generating session-encoded links doesn't
* mean someone else won't try
*/
if (httpRequest.isRequestedSessionIdFromURL()) {
HttpSession session = httpRequest.getSession();
if (session != null) {
session.invalidate();
}
}
HttpServletResponseWrapper wrappedResponse = new ResponseWrapper(httpResponse);
chain.doFilter(request, wrappedResponse);
}
@Override
@SuppressWarnings("unused")
public void init(FilterConfig arg0) throws ServletException {
}
/**
* wraps response and prevense jsessionid from being encoded on the output.
*/
private static class ResponseWrapper extends HttpServletResponseWrapper {
ResponseWrapper(HttpServletResponse httpResponse) {
super(httpResponse);
}
@Override
public String encodeRedirectUrl(String uri) {
return uri;
}
@Override
public String encodeRedirectURL(String uri) {
return uri;
}
@Override
public String encodeUrl(String uri) {
return uri;
}
@Override
public String encodeURL(String uri) {
return uri;
}
}
}