0

My application receives an encrypted payload and I have to decrypt each value of the object. After, I have to encrypt the payload with the same format and send response.

What I need is an method to intercept the payload before it reach the controller to decrypt and intercept response to encrypt data.

I'm trying use a filter of javax.servlet but I don`t know how to get the body, change his value and set it back.

I already tried an interceptor but I had the same problem to change request body.


@Component
@Order(1)
public class CryptoFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        // code to decrypt request body goes here
        filterChain.doFilter(request, response);
        // code to encrypt response body goes here
    }
}

The request body cames like this:

{
    "key1": "098f6bcd4621d373cade4e832627b4f6",
    "key2": "098f6bcd4621d373cade4e832627b4f6",
    "key3": {
        "key4": "098f6bcd4621d373cade4e832627b4f6"
    }
}

And after filter I need this on controller:

{
    "key1": "decrypted",
    "key2": "decrypted",
    "key3": {
        "key4": "decrypted"
    }
}
Pedro
  • 41
  • 1
  • 2
  • 8
  • this might help https://stackoverflow.com/questions/34155480/how-to-change-servlet-request-body-in-java-filter – codebrane Sep 10 '19 at 13:52
  • It helped to a better understanding. I've found [this question](https://stackoverflow.com/questions/45699380/how-to-rewrite-post-request-body-on-httpservletrequest?rq=1) and this approach worked. I'm using a ControllerAdvice to obtain the object before it reach the controller then I don't have the IllegalStateException throwed when we read the InputStrem more than once, which happens when using filter – Pedro Sep 11 '19 at 18:36

1 Answers1

0

If your application uses the Spring framework, you can use AOP (Aspect Oriented Programming) to define an Aspect around your filter which would decrypt the data, call the filter method, and intercept the response to re-encrypt it.

https://docs.spring.io/spring/docs/2.5.x/reference/aop.html

Tom Elias
  • 751
  • 6
  • 15
  • 1
    Thank for your attention. I'll take a look into it with a little more careful. Now I'm using ControllerAdvice and it seems more practical. – Pedro Sep 11 '19 at 18:53