Created
September 11, 2011 11:18
-
-
Save valotas/1209461 to your computer and use it in GitHub Desktop.
Decorator pattern with HttpServerRequest
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
public class HttpServletRequestDecoratorFilter implements Filter { | |
@Override | |
public void init(FilterConfig filterConfig) throws ServletException { | |
//do nothing | |
} | |
@Override | |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { | |
request = decorate(request); | |
chain.doFilter(request, response); | |
} | |
private ServletRequest decorate(ServletRequest request) { | |
try { | |
HttpServletRequest req = (HttpServletRequest) request; | |
return new XFFAwareReq(req); | |
} | |
catch (ClassCastException e) { | |
// As we are not able to cast the request to an Http one, we just return the same object | |
return request; | |
} | |
} | |
@Override | |
public void destroy() { | |
// Do nothing | |
} | |
} |
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
public class XFFAwareReq extends HttpServletRequestWrapper { | |
public XFFAwareReq(HttpServletRequest request) { | |
super(request); | |
} | |
@Override | |
public String getRemoteAddr() { | |
String xff = getXForwardedFor(); | |
return xff != null ? xff : super.getRemoteAddr(); | |
} | |
public String getXForwardedFor() { | |
String xff = getHeader("X-Forwarded-For"); | |
if (xff == null || "".equals(xff)) return null; | |
return getIpFromXFF(xff); | |
} | |
protected static final String getIpFromXFF(String xff) { | |
//extract and return the ip from the X-Forwarded-For header | |
} | |
} |
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
public class XSSAwareReq extends HttpServletRequestWrapper { | |
protected XSSAwareReq(HttpServletRequest req) { | |
super(req); | |
} | |
@Override | |
public String getParameter(String name) { | |
return super.getParameter(name) | |
.replaceAll("<", "<") | |
.replaceAll(">", ">") | |
.replaceAll("\\(", "(") | |
.replaceAll("\\)", ")") | |
.replaceAll("'", "'") | |
.replaceAll("eval\\((.*)\\)", "") | |
.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"") | |
.replaceAll("script", ""); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment