Search code examples
javaspringspring-bootspring-mvcauditing

In Spring how to audit endpoint communication?


My intent is to audit the data exchange through the endpoints of my application. I wanna retrieve the json exchanged throught the endpoints and store it in the database. For storing the json data I will use Javes (https://javers.org/) but I still need to figure out how to obtain the endpoint data.


Solution

  • You can write interceptor to do additional processing of requests and responses flowing through your application. If you are using spring it is very easy to implement. Here is an example:

    @Component
    public class RestInterceptor implements ClientHttpRequestInterceptor {
    
     @Override
     public ClientHttpResponse intercept(HttpRequest request, byte[] body,
      ClientHttpRequestExecution execution) throws IOException {
      traceRequest(request, body);
      ClientHttpResponse response = execution.execute(request, body);
      traceResponse(response);
      return response;
     }
    
     private void traceRequest(HttpRequest request, byte[] body) throws IOException {
       //track request here
     }
    
    
     private void traceResponse(ClientHttpResponse response) throws IOException {
        //track response here
     }
    
    }
    

    Now register it with your rest template

    restTemplate.setInterceptors(Collections.singletonList(new RestInterceptor ()));