上传文件过滤

文件上传时,判断文件是否合法

第一种通过系统设置,添加后缀限制。

第二种:通过gateway做一个拦截器

package com.je.gateway.filter;

import com.google.common.base.Strings;
import org.apache.servicecomb.core.Invocation;
import org.apache.servicecomb.foundation.common.http.HttpStatus;
import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
import org.apache.servicecomb.swagger.invocation.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.Part;
import java.util.Arrays;
import java.util.List;

@Component
public class GatewayFileUploadTypeFilter extends AbstractHttpServerFilter {

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

    // 禁止的文件类型
    private static final List<String> DISALLOWED_FILE_EXTENSIONS = Arrays.asList(".jsp", ".html");

    @Override
    public int getOrder() {
        return 51;
    }

    @Override
    public Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx requestEx) {
        HttpServletRequestEx hsre = invocation.getRequestEx();
        // 注意:nginx服务需要把ip传过来才可以,需要加nginx配置
        // 多次反向代理后会有多个ip值,第一个ip才是真实ip
        String ip = hsre.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() > 0 && !"unKnown".equalsIgnoreCase(ip)) {
            int index = ip.indexOf(",");
            if (index != -1) {
                ip = ip.substring(0, index);
            }
        }
        // 如果这个ip属于白名单,放开
        if (!Strings.isNullOrEmpty(ip) && ip.equals("xxx.xxx.xxx.xxx")) {
            return null;
        }

        try {
            if ("POST".equalsIgnoreCase(requestEx.getMethod()) && requestEx.getContentType() != null &&
                    requestEx.getContentType().toLowerCase().startsWith("multipart/")) {

                for (Part part : requestEx.getParts()) {
                    String fileName = part.getSubmittedFileName();
                    if (isDisallowedFileType(fileName)) {
                        logger.warn("Unauthorized file type: {}", fileName);
                        return Response.create(new HttpStatus(401, "Unauthorized"), "文件类型异常!");
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Error while checking file types", e);
            return Response.create(new HttpStatus(500, "Internal Server Error"), "文件类型检查时发生错误!");
        }

        return null;
    }

    private boolean isDisallowedFileType(String fileName) {
        if (fileName != null) {
            for (String extension : DISALLOWED_FILE_EXTENSIONS) {
                if (fileName.toLowerCase().endsWith(extension)) {
                    return true;
                }
            }
        }
        return false;
    }

}

第三种方式:修改document校验方法

    @Override
    public void checkFileSuffix(String fileName) {
        List<String> list = new ArrayList<>();
        String suffixs = systemSettingRpcService.findSettingValue("JE_DOCUMENT_FILE_SUFFIX");
        if (StringUtil.isNotEmpty(suffixs)) {
            list = Arrays.asList(suffixs.split(","));
        }
        if (!DocumentUtil.checkFileSuffix(fileName, list)) {
            throw new DocumentException(MessageUtils.getMessage("document.file.suffix.error", suffixs), DocumentExceptionEnum.DOCUMENT_ERROR);
        }
        //加一个自定义判断,如果文件后缀是什么,直接抛异常
        String[] arr = fileName.split("\\.");
        String suffix = arr[arr.length - 1];
        if (suffix.indexOf("jsp") >= 0) {
            throw new DocumentException(String.format("系统禁止上传%s文件类型", suffix), DocumentExceptionEnum.DOCUMENT_ERROR);
        }

    }

最后编辑: 于春辉  文档更新时间: 2024-09-13 11:32   作者:于春辉