预防Dos攻击

Dos----拒绝服务攻击,一般是构造特殊的输入,使得后台的处理耗时远超正常水平,随着请求越来越多,后台服务越发疲于奔命,最后因资源耗尽,无法再接受新的请求,最终造成拒绝服务的效果。

特殊输入例如:
分页查询时传一个很大的pageSize;
入参是一个很大的集合。

对于前者,做一个公共函数检查pageSize的大小,确定合理的范围即可。
对于后者,往往是在post请求里,可以做一个filter来处理所有的incoming request。参考了一些资料,样例代码如下:

@Component
public class BodySizeLimitFilter implements Filter {

    private static final List<String> METHODS_WITH_BODY = Collections.unmodifiableList(
        Arrays.asList("POST", "PUT", "OPTIONS", "DELETE", "PATCH"));

    private static final String CONTENT_LENGTH_HEADER = "Content-Length";

    private static final int TOO_LARGE_STATUS = 413;

    @Value("${reqbody.maxsize:4096}")
    private long contentLengthLimit;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        if (!METHODS_WITH_BODY.contains(httpServletRequest.getMethod())) {
            chain.doFilter(httpServletRequest, httpResponse);
            return;
        }

        long contentSize = getContentLength(httpServletRequest);

        if (contentSize > contentLengthLimit) {
            resetRespAndSetStatus(httpResponse, TOO_LARGE_STATUS);
        } else {
            chain.doFilter(request, response);
        }
    }

    private void resetRespAndSetStatus(HttpServletResponse response, int status) {
        response.reset();
        response.setStatus(status);
    }

    private long getContentLength(HttpServletRequest httpRequest) {
        String contentLength = httpRequest.getHeader(CONTENT_LENGTH_HEADER);
        return safeToLong(contentLength, 0);
    }
}

你可能感兴趣的:(安全,java,开发语言)