java - How to alter the body of a http response in a filter -
i attempting use filter check html tags in response body. problem if alter body in filter, isn't altered when gets client. tried solution shown here: looking example inserting content response using servlet filter didn't help.
i have 2 filters. securewrapperfilter
wraps request/response objects in our custom wrapper, , xssfilter
uses owasp encode encode html content. filters this:
public class securewrapperfilter implements filter { @override public void init(final filterconfig filterconfig) throws servletexception { } @override public void dofilter(final servletrequest request, final servletresponse response, final filterchain chain) throws ioexception, servletexception { final servletrequestwrapper securityrequest = new servletrequestwrapper((httpservletrequest)request); final servletresponsewrapper securityresponse = new servletresponsewrapper((httpservletresponse)response); esapi.httputilities().setcurrenthttp(securityrequest, securityresponse); chain.dofilter(esapi.currentrequest(), esapi.currentresponse()); } @override public void destroy() { } }
and:
public class xssfilter implements filter { @override public void init(final filterconfig filterconfig) throws servletexception { } @override public void dofilter(final servletrequest request, final servletresponse response, final filterchain chain) throws ioexception, servletexception { final servletrequestwrapper requestwrapper = (servletrequestwrapper)request; final string body = encode.forhtmlcontent(requestwrapper.getbody()); requestwrapper.setbody(body); chain.dofilter(requestwrapper, response); final servletresponsewrapper responsewrapper = (servletresponsewrapper)response; final byte[] copy = responsewrapper.getcopy(); final string oldbody = new string(copy, response.getcharacterencoding()); final string newbody = encode.forhtmlcontent(oldbody); if (!stringutils.equals(oldbody, newbody)) { responsewrapper.getresponse().getoutputstream().write(newbody.getbytes()); } } @override public void destroy() { } }
if add debug logging, can see securityresponse
has modified body in securewrapperfilter, on client side, body looks if never modified.
any suggestions appreciated. thanks.
the problem in xssfilter, appending new response body onto old one. causing invalid json {"x"="y"}{"escapedx"="escapedy")
our client deserializer printing first json object {"x"=y"}
seeing on client side.
to resolve problem, added following line xssfilter:
responsewrapper.getresponse().resetbuffer();
before
responsewrapper.getresponse().getoutputstream().write(newbody.getbytes());
this clears buffer, allowing me rewrite on line below. json on client side looks like: {"escapedx"="escapedy"}
Comments
Post a Comment