1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
@Slf4j @Component public class ContentTypeValidationFilter extends OncePerRequestFilter {
private static final List<String> METHODS_TO_VALIDATE = Arrays.asList("POST", "PUT", "PATCH");
private static final List<String> ALLOWED_CONTENT_TYPES = Arrays.asList( "application/json", "application/x-www-form-urlencoded", "multipart/form-data" );
private static final List<String> WHITELIST_PATHS = Arrays.asList( "/upload", "/swagger", "/v2/api-docs", "/v3/api-docs" );
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String method = request.getMethod(); String path = request.getRequestURI(); if (!METHODS_TO_VALIDATE.contains(method)) { filterChain.doFilter(request, response); return; } if (isWhitelistPath(path)) { filterChain.doFilter(request, response); return; } String contentType = request.getContentType(); if (contentType == null || contentType.isEmpty()) { log.warn("请求缺少Content-Type header, path: {}, method: {}", path, method); sendErrorResponse(response, "请求必须包含Content-Type"); return; } String baseContentType = contentType.split(";")[0].trim().toLowerCase(); boolean isValid = ALLOWED_CONTENT_TYPES.stream() .anyMatch(allowed -> baseContentType.startsWith(allowed)); if (!isValid) { log.warn("不支持的Content-Type: {}, path: {}, method: {}", contentType, path, method); sendErrorResponse(response, "不支持的Content-Type: " + baseContentType); return; } filterChain.doFilter(request, response); }
private boolean isWhitelistPath(String path) { return WHITELIST_PATHS.stream().anyMatch(path::startsWith); }
private void sendErrorResponse(HttpServletResponse response, String message) throws IOException { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentType("application/json;charset=UTF-8"); ResponseResult result = ResponseResult.errorResult( AppHttpCodeEnum.SYSTEM_ERROR.getCode(), message ); response.getWriter().write(JSON.toJSONString(result)); } }
|