Intercept HTTP requests in server java - java

I need to implemented something like a filter or listener, that intercepts HTTP requests and retrieves the HTTP headers for various purposes.
I use Java, Jboss application server and web services. I want this filtering system to be performed prior to the Web Services call - was thinking about aspects but they do not hold the HTTP related stuff. After the filter, the service call should be carried out.
Jax-WS handlers don't work for me either as they only hold the SOAP payload.
Any ideas?
Thanks in advance.

can you not create a servlet filter which intercepts all the requests coming to your webservice engine? If you are using Axis or anyother SOAP engine, I hope you should be able to create a filter that intercepts all the requests coming to the main servlet that the SOAP engine provides.
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException
{
HttpServletRequest httpRequest=(HttpServletRequest)request;
HttpServletResponse httpResponse=(HttpServletResponse)response;
Enumeration headerNames = httpRequest.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
out.println(headerName);
out.println(request.getHeader(headerName));
}
chain.doFilter(request,response);
}

Use libpcap and the Java interface jNetPcap.

Related

How can I check if servlet request is internal with Jetty?

We have a embedded Jetty 10.0.12 server, configure everything programmably (no web.xml) and already have a few servlets registered. We want to add a new servlet for an internal API. I have already done this. We now want to secure it. Security would be pretty simple: if the request did not come from within the server, reject it. This is good enough because we employ other security standards in the other servlets. I know where to start: create and register a filter:
public class InternalFilter implements Filter {
#Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
// TODO: Check if request is internal.
// I.e., came from another registered servlet in the same JVM.
// If it is internal, then `chain.doFilter`.
}
}
I do not know how to proceed from here.
I'll start by assuming that "internal" means you are using either RequestDispatcher.include() or RequestDispatcher.forward().
If so, then you can check the HttpServletRequest.getDispatcherType() value.
Value
Meaning
DispatcherType.FORWARD
Request arrived from a call to RequestDispatcher.forward().
DispatcherType.INCLUDE
Request arrived from a call to RequestDispatcher.include().
DispatcherType.REQUEST
Request arrived from the beginning of the server handling tree.
DispatcherType.ASYNC
Request arrived from call to HttpServletRequest.startAsync()
DispatcherType.ERROR
Request arrived from error handling (either an unhandled exception, or from a call to HttpServletResponse.sendError()

Springboot: Modify incoming Web service response

I'm working on a springboot service currently and it needs to have the ability to modify the incoming response body received from various web service calls made by itself.
I googled around a lot and could find info about servlet filters, spring interceptors etc. But all of them sit between this service and its calling clients.
But I'm looking for a component which can sit between this service and the other services that it calls. The closest one I could find was spring's ClientHttpRequestInterceptor, but it doesn't seems to have the ability to modify response body.
Client apps ---> 2. My Springboot service. ---> 3. Other web services
I need to have a component between 2 and 3 here.
Can someone please shed some light on this? Thank you.
P.S: Also I know jaxrs ClientRequestFilter does the trick, but I need a solution for spring RestTemplate based service calls and not for jaxrs based.
In Spring RestTemplate allows us to add interceptors that implement ClientHttpRequestInterceptor interface .
The intercept(HttpRequest, byte[], ClientHttpRequestExecution) method of this interface will intercept the given request and return the response by giving us access to the request,
ClientHttpRequestExecution argument to do the actual execution, and pass on the request to the subsequent process chain
public class BodyInterceptor
implements ClientHttpRequestInterceptor {
#Override
public ClientHttpResponse intercept(
HttpRequest request,
byte[] body,
ClientHttpRequestExecution execution) throws IOException {
ClientHttpResponse response = execution.execute(request, body);
response.getHeaders().add("Iphone_version", "proX");
return response;
}
}
Spring AOP can help in your scenario. It can act as a component before invoking another controller or component.

How to support batch web api request processing using Spring/Servlets

We have our Web API written in using RESTEasy. We would like to provide support for Batch requests processing the way Google Batch request processing works.
Following is the approach which are using currently,
We have a filter which accepts incoming multipart request. This filter then creates multiple mock requests and response objects and then calls chain.doFilter using these mock requests.
public class BatchRequestProcessingFilter extends GenericFilterBean {
#Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
MockHttpServletRequest[] mockRequests = BatchRequestProcessorUtils.parseRequest(request);
MockHttpServletResponse[] mockResponses = new MockHttpServletResponse[mockRequests.length];
for(int i=0 ; i <= mockRequests.length ; i++ ) {
chain.doFilter(mockRequests[i], mockResponses[i], chain);
}
BatchRequestProcessingUtils.populateResponseFromMockResponses(res, mockResponses);
}
}
MockHttpServletResponse class returns a dummy OutputStream which wraps ByteArrayOutputStream.
BatchRequestProcessorUtils parses the multipart request and returns the mock request which wraps actual request but returns the header specified in split body of the actual request body.
I could not find any existing library which supports batch request processing. So my question is that, is this the correct approach to support batch request or is there any standard way which should be used?
Note that we are using Tomcat 8.
Sachin Gorade. I have not heard about such libraries, but I think your approach is reasonable. If I had to solve that problem, I would think like this:
In our HTTP servlets we can process requests only separately, and it is the reason why we should wrap all requests, that we want to send, into another single request at client side.
As on our server side we have only one request, then we should unwrap all requests we have put into it. And, because we dont know how to process each request in our batch mechanizm - we shold send it through all filters/servlets. Also it is a reason to put our batch filter at the first position in the order.
Eventually, when all requests has been processed, we should send a response back to the client. And again, to do that we should wrap all responses into a single one.
At the client side we should unwrap responses and send each of that to some objects, that can process it.
In my oponion there should be two mechanizms:
Batch sender for client side, that is responsible for collecting and wrapping requests, unwrapping responses and sending them to theirs processors(methods that process regular responses).
Batch processor for server side, that is responsible for unwrapping requests, and collecting and wrapping responses.
Of course, that two parts may be coupled (i.g. to have shared "Wrapper" module), because objects we must be wrapped and unwrapped in the same way.
Also, if I worked on it, I would try to develop the client side mechanizm like a decorator upon a class that I use to send regular requests. In that case, I would be able to substitute regular/batch mode anytime I need to do it.
Hope my opinion is helpful for you.

Restricting access to localhost for Java Servlet endpoint

In short - I would like to add such service endpoints to my servlet that can only be called from localhost. The restriction should be coded in the servlet itself, i.e it should not depend on Tomcat/Apache to be configured in a certain way. At the same time, there are many other, existing endpoints that should be reachable externally.
Longer description - I am creating an HTTP API that 3rd parties can implement to integrate with my application. I am also supplying a default implementation, bundled together with my app, that customers with simple requirements can use, without having to implement anything.
The endpoints of my default implementation should be reachable only for my app, which happens to be the same servlet as the one supplying the implementation, i.e it runs on the same host. So for security reasons (the API is security related), I want my implementation to be usable only for my app, which in the first round means restricting access to localhost for a set of HTTP endpoints.
At the same time, I don't want to rely on customers setting up their container/proxy properly, but do the restriction in my servlet, so that there are no changes required for existing installations.
So far the only idea I had was to check the requestor's IP addess in a servlet filter - so I am wondering if there is a better, more sophisticated way.
I think you should add Web Filter to your application and check your url in doFilter method. Check request.getRemoteAddr() and endpoint link you can put in urlPattern.
Like this:
#WebFilter(urlPatterns = "/*")
public class RequestDefaultFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (isForbidden(request, response))
return;
else
chain.doFilter(request, response);
}
}
isForbidden implementation is up to you. In response you just send 403 error code for example.
You can check make same check in servlet and send in response 403 error.

How do I avoid creating a session?

My setup is as follows
A main application servlet accessible under /myApp/mainServlet/
A little "hand made" soap proxy that adds security headers (usernames, passwords) to soap calls coming from a client
A Flex client that talks to the main servlet (through a BlazeDS interface), and sends some soap calls to a third party through this soap proxy
The flex client has a session id which is set when it first talks to the main servlet and it returns a HTTP header such as "Set-Cookie: "JSESSION: something; Path=/myApp". This cookie is then sent the the server to inform of which session the client is associated to.
The problem is that the little soap proxy also returns a cookie with a session id (for each call made through it) - and the Flex client then uses these cookies when talking to the main servlet. These other session ids are unknown to it, and then of course nothing works ...
I do not want a session cookie to be returned from the soap proxy, and I have verified that the problem would be solved by doing so by telling an Apache front-end to strip all "Set-Cookie" headers coming from the soap proxy. Unfortunately (due to some setup restrictions), this is not a way I can go in production, and so I will need to fix it programmatically.
How can I make the servlet not try to set any session ids? I believe I have seen ways of telling Jetty (the app server) not to send sessions ids, but that would also affect the main servlet's ability to do so as well, and is also not portable.
The proxy servlet is a very basic Spring Controller (just implementing the interface), so basically just a bare bone servlet.
Removing the cookie can be done with res.setHeader("Set-Cookie", null);
Edit: It is good to know, that this removes all cookies, since they are all set in the same header.
I recommend that you don't do it in your servlet, a Filter is better, because it's less intrusive, something like:
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
HttpServletResponse res = (HttpServletResponse) response;
try
{
chain.doFilter(request, res);
}
finally
{
res.setHeader("Set-Cookie", null);
}
}
This solution is inspired by this article at randomcoder.

Categories