如何在HttpServletRequest上重写POST请求体

时间:2017-08-15 18:40:50

标签: java servlets post encryption

我正在使用过滤器,我必须在其中获取请求有效负载,解密它,检查它是否是有效的JSON以及是否继续使用链并转到我的服务。问题是,到目前为止,我还没有找到改写身体的方法。为什么我要重写它?由于服务期望JSON并且请求在正文中有加密文本,因此一旦我解密它,我希望正文是解密的JSON。此外,一旦我从服务返回,我应该重写响应以加密json。我已经阅读了很多论坛和问题,但无法找到有效的解决方案。

这是我的代码:

RequestLoginFilter.java

    @WebFilter("/RequestLoginFilter")
public class RequestLoginFilter implements Filter{

    protected final static Log logger = LogFactory.getLog(RequestLoginFilter.class);

    private ServletContext context;

    private CryptoUtil crypto;

    public void init(FilterConfig fConfig) throws ServletException {
        this.context = fConfig.getServletContext();
        this.context.log("RequestLoggingFilter initialized");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//       use wrapper to read multiple times the content
        AuthenticationRequestWrapper req = new AuthenticationRequestWrapper((HttpServletRequest) request);
        HttpServletResponse resp = (HttpServletResponse) response;

        String payload = req.getPayload();
        try {
            String decryptedPayload = crypto.decrypt(payload);
            JSONUtils.convertJSONStringToObject(decryptedPayload, LoginTokenTO.class);
        } catch (GeneralSecurityException e) {
            logger.error("Error when trying to decrypt payload '"+payload+"'");
            throw new ServletException("Error when trying to decrypt payload '"+payload+"'", e);
        }
        chain.doFilter(req, resp);
        System.out.println("a ver");
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}

还有包装器,以防万一:

AuthenticationRequestWrapper.java

public class AuthenticationRequestWrapper extends HttpServletRequestWrapper {

    protected final static Log logger = LogFactory.getLog(AuthenticationRequestWrapper.class);

    private final String payload;

    public AuthenticationRequestWrapper (HttpServletRequest request) throws AuthenticationException {
        super(request);

        // read the original payload into the payload variable
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            // read the payload into the StringBuilder
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                // make an empty string since there is no payload
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            logger.error("Error reading the request payload", ex);
            throw new AuthenticationException("Error reading the request payload", ex);
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException iox) {
                    // ignore
                }
            }
        }
        payload = stringBuilder.toString();
    }

    @Override
    public ServletInputStream getInputStream () throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(payload.getBytes());
        ServletInputStream inputStream = new ServletInputStream() {
            public int read () 
                throws IOException {
                return byteArrayInputStream.read();
            }
        };
        return inputStream;
    }

    public String getPayload() {
        return payload;
    }
}

希望有人在这里知道如何让这个工作。

先谢谢你们。

1 个答案:

答案 0 :(得分:1)

虽然你所要求的可能在技术上是可行的,但对我来说这听起来并不合适。

您需要的是位于传入请求(端点)和服务之间的安全层。重写请求的主体是一件奇怪的事情(这可能解释了为什么你有问题)。您是否希望在Filter中完成此操作?毕竟,filters旨在过滤请求,而不是重写请求;)

更合乎逻辑/透明的解决方案是让您的端点接受所有传入请求,在将请求传递到服务层之前对其进行解密和验证。像这样:

public void handleRequest(Request request) {
    try {
        IncomingRequest x = securityManager.decrypt(request);
        Response r = myService.handleRequest(x);
        handleResponse(securityManager.encrypt(r));
    }catch(InvlidateMessage x) {
        handleInvalidMessage...
    }catch(BusinessException x) {
        handleBusinessException...
    }
}