How avoid input stream closed in dispatcherServlet after a filter

Daniela Morais :

I need persist all information about requests/responses that are sent for application as http status, current time, token, request URI etc. It's an API and the resources are:

  • POST localhost:8080/v1/auth/login with email and password in request for authentication. Response is a JWT token.

  • GET localhost:8080/v1/auth/rules with a token in header of request. Response is a body with information about token's owner such as email and name.

To achieve this, my method override doDispatch method:

LogDispatcherServlet

@Component
public class LogDispatcherServlet extends DispatcherServlet {

    @Autowired
    private LogRepository logRepository;

    private static final Logger logger = LoggerFactory.getLogger(LogDispatcherServlet.class);

    @Override
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (!(request instanceof ContentCachingRequestWrapper)) {
            request = new ContentCachingRequestWrapper(request);
        }
        if (!(response instanceof ContentCachingResponseWrapper)) {
            response = new ContentCachingResponseWrapper(response);
        }
        HandlerExecutionChain handler = getHandler(request);

        try {
            super.doDispatch(request, response);
        } finally {
            try {
                ApiLog log = ApiLog.build(request, response, handler, null);
                logRepository.save(log);
                updateResponse(response);
            } catch (UncheckedIOException e) {
                logger.error("UncheckedIOException", e);
            } catch (Exception e) {
                logger.error("an error in auth", e);
            }
        }
    }

    private void updateResponse(HttpServletResponse response) throws IOException {
        ContentCachingResponseWrapper responseWrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
        responseWrapper.copyBodyToResponse();
    }

}

ApiLog.build is responsible for getting sample information about request and LogDispatcherServlet Works fine for a GET in localhost:8080/v1/auth/rules.

ApiLog

public static ApiLog build(HttpServletRequest request, HttpServletResponse response, HandlerExecutionChain handler, Authentication auth) {
        ApiLog log = new ApiLog();
        log.setHttpStatus(response.getStatus());
        log.setHttpMethod(request.getMethod());
        log.setPath(request.getRequestURI());
        log.setClientIp(request.getRemoteAddr());
        try {
            if (request.getReader() != null) {
                log.setBodyRequest(getRequestPayload(request));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (handler != null) {
            log.setJavaMethod(handler.toString());
        }
        if (request.getHeader("Authorization") != null) {
            log.setToken(request.getHeader("Authorization"));
        } else if (response.getHeader("Authorization") != null) {
            log.setToken(response.getHeader("Authorization"));
        }
        log.setResponse(getResponsePayload(response));
        log.setCreated(Instant.now());
        logger.debug(log.toString());
        return log;
    }

    @NotNull
    private static String getRequestPayload(HttpServletRequest request) {
        ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
        try {
            return wrapper
                    .getReader()
                    .lines()
                    .collect(Collectors.joining(System.lineSeparator()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    @NotNull
    private static String getResponsePayload(HttpServletResponse responseToCache) {
        ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(responseToCache, ContentCachingResponseWrapper.class);
        if (wrapper != null) {
            byte[] buf = wrapper.getContentAsByteArray();
            if (buf.length > 0) {
                int length = Math.min(buf.length, 5120);
                try {
                    return new String(buf, 0, length, wrapper.getCharacterEncoding());
                } catch (UnsupportedEncodingException ex) {
                    logger.error("An error occurred when tried to logging request/response");
                }
            }
        }
        return "{}";
    }

My biggest problem is: I'm using Spring Security for generate a JWT Token so all requests send to /v1/auth/login are redirect for a filter.

AppSecurity

@Configuration
@EnableWebSecurity
public class AppSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .and()
                .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
                        UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService);
    }

}

After a successful authentication, filter must call LogDispatcherServlet for persist what was the request and what will be the response. There's no Controller for /login, just JWTLoginFilter.

JWTLoginFilter

public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {

    @Autowired
    JWTLoginFilter(String url, AuthenticationManager authManager) {
        super(new AntPathRequestMatcher(url));
        setAuthenticationManager(authManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {

        AccountCredentials credentials = new ObjectMapper()
                .readValue(request.getInputStream(), AccountCredentials.class);

        return getAuthenticationManager().authenticate(
                new UsernamePasswordAuthenticationToken(
                        credentials.getUsername(),
                        Md5.getHash(credentials.getPassword()),
                        Collections.emptyList()
                )
        );
    }

    @Override
    protected void successfulAuthentication(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain,
            Authentication auth) throws IOException, ServletException {

        TokenAuthenticationService.addAuthentication(response, auth.getName());
        //Must call LogDispatcherServlet
        filterChain.doFilter(request, response);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        super.unsuccessfulAuthentication(request, response, failed);

        //Must call LogDispatcherServlet
    }

}

But it doesn't work for /login. When ApiLog try to get request body in getRequestPayload I get an java.io.IOException: Stream closed

What can I do for avoid this? JWTLoginFilter need to know request body for authentication and LogDispatcherServlet too but request.getInputStream() is called in attemptAuthentication. Is there another solution less complex?

benjamin.d :

I don't think you need to update Spring's DispatcherServlet. I would just create a filter (at first position in the chain) that wraps the original request / response in an object that allows caching (such as ContentCachingRequestWrapper / ContentCachingResponseWrapper).

In your filter you just need to do something like:

doFilter(chain, req, res) {

   ServletRequest wrappedRequest = ...
   ServletResponse wrappedResponse = ...   

   chain.doFilter(wrappedRequest, wrappedResponse);

}

And you can register a HandlerInterceptor

public class YourHandlerIntercepter extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) 

            ApiLog log = ApiLog.build(request, response, handler, null);
            logRepository.save(log);
        }
        return true;
    }
}

You finally need to change your ApiLog method so it uses MethodHandler instead of a HandlerExecutionChain

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=457921&siteId=1