『博客开发日记』之对前台工程进行安全性升级

本文最后更新于 2026年5月4日 晚上

升级 SensitiveUtilServiceImpl


前言

书再再接上回

既然都对前台做了这么多安全性改造了

干脆直接对前台工程的安全防护进行升级

主要升级是 增加XSS防护 和 Content-Type验证

代码实现

使用 XssUtils 来过滤恶意脚本

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
/**
* XSS防护工具类
* 用于过滤用户输入中的恶意脚本
*
* @author mengze
*/
public class XssUtils {

/**
* HTML转义,防止XSS攻击
*
* @param input 原始输入
* @return 转义后的安全字符串
*/
public static String escapeHtml(String input) {
if (input == null || input.isEmpty()) {
return input;
}
return HtmlUtils.htmlEscape(input);
}

/**
* 批量HTML转义
*
* @param inputs 原始输入数组
* @return 转义后的安全字符串数组
*/
public static String[] escapeHtml(String... inputs) {
if (inputs == null || inputs.length == 0) {
return inputs;
}

String[] escaped = new String[inputs.length];
for (int i = 0; i < inputs.length; i++) {
escaped[i] = escapeHtml(inputs[i]);
}
return escaped;
}

/**
* 清理危险字符,保留基本格式
* 适用于需要保留部分HTML格式的场景(如富文本编辑器)
*
* @param input 原始输入
* @return 清理后的字符串
*/
public static String cleanDangerousChars(String input) {
if (input == null || input.isEmpty()) {
return input;
}

// 移除script标签及其内容
input = input.replaceAll("(?i)<script[^>]*>.*?</script>", "");

// 移除iframe标签
input = input.replaceAll("(?i)<iframe[^>]*>.*?</iframe>", "");

// 移除on事件处理器(如onclick, onerror等)
input = input.replaceAll("(?i)\\s*on\\w+\\s*=\\s*[\"'][^\"']*[\"']", "");
input = input.replaceAll("(?i)\\s*on\\w+\\s*=\\s*[^\\s>]*", "");

// 移除javascript:伪协议
input = input.replaceAll("(?i)javascript:", "");

// 移除vbscript:伪协议
input = input.replaceAll("(?i)vbscript:", "");

return input;
}

/**
* 验证URL是否安全
* 防止javascript:、data:等危险协议
*
* @param url 待验证的URL
* @return true-安全,false-不安全
*/
public static boolean isSafeUrl(String url) {
if (url == null || url.isEmpty()) {
return true;
}

String lowerUrl = url.toLowerCase().trim();

// 检查危险协议
String[] dangerousProtocols = {
"javascript:", "data:", "vbscript:", "file:", "about:"
};

for (String protocol : dangerousProtocols) {
if (lowerUrl.startsWith(protocol)) {
return false;
}
}

return true;
}
}

在 SysUserServiceImpl 的 updateUserInfo 和 userRegister 方法中调用



重点还要在评论接口里添加xss防护


1
2
3
4
5
6
7
8
9
10
11
12
13
//XSS防护:转义用户输入的内容
if (StringUtils.hasText(comment.getContent())) {
comment.setContent(XssUtils.escapeHtml(comment.getContent()));
}
if (StringUtils.hasText(comment.getNickname())) {
comment.setNickname(XssUtils.escapeHtml(comment.getNickname()));
}
if (StringUtils.hasText(comment.getPersonalWebsite())) {
// 验证URL安全性
if (!XssUtils.isSafeUrl(comment.getPersonalWebsite())) {
return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "个人网址包含不安全的协议");
}
}

再使用 ContentTypeValidationFilter 防止Content-Type伪造攻击

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
/**
* Content-Type验证过滤器
* 防止Content-Type伪造攻击
*
* @author mengze
*/
@Slf4j
@Component
public class ContentTypeValidationFilter extends OncePerRequestFilter {

/**
* 需要验证Content-Type的请求方法
*/
private static final List<String> METHODS_TO_VALIDATE = Arrays.asList("POST", "PUT", "PATCH");

/**
* 允许的Content-Type列表
*/
private static final List<String> ALLOWED_CONTENT_TYPES = Arrays.asList(
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data"
);

/**
* 白名单路径(不需要验证Content-Type)
*/
private static final List<String> WHITELIST_PATHS = Arrays.asList(
"/upload", // 文件上传接口
"/swagger", // Swagger文档
"/v2/api-docs", // Swagger API文档
"/v3/api-docs" // Swagger API文档
);

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

String method = request.getMethod();
String path = request.getRequestURI();

// 只验证POST、PUT、PATCH请求
if (!METHODS_TO_VALIDATE.contains(method)) {
filterChain.doFilter(request, response);
return;
}

// 检查是否在白名单中
if (isWhitelistPath(path)) {
filterChain.doFilter(request, response);
return;
}

// 获取Content-Type
String contentType = request.getContentType();

// Content-Type不能为空
if (contentType == null || contentType.isEmpty()) {
log.warn("请求缺少Content-Type header, path: {}, method: {}", path, method);
sendErrorResponse(response, "请求必须包含Content-Type");
return;
}

// 验证Content-Type是否合法(忽略charset等参数)
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));
}
}

在 WebConfig 中配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Content-Type验证过滤器
* 防止Content-Type伪造攻击
* 如果前端代码规范,所有接口都正确设置Content-Type,则启用
*/
@Bean
public FilterRegistrationBean<ContentTypeValidationFilter> contentTypeFilter()
{
FilterRegistrationBean<ContentTypeValidationFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(new ContentTypeValidationFilter());
registration.addUrlPatterns("/*");
registration.setOrder(1);
return registration;
}



PS:该系列只做为作者学习开发项目做的笔记用

不一定符合读者来学习,仅供参考


预告

后续会记录博客的开发过程

每次学习会做一份笔记来进行发表

“一花一世界,一叶一菩提”


版权所有 © 2026 云梦泽
欢迎访问我的个人网站:https://hgt12.github.io/


『博客开发日记』之对前台工程进行安全性升级
http://example.com/2026/05/04/『博客开发日记』之对前台工程进行安全性升级/
作者
云梦泽
发布于
2026年5月4日
更新于
2026年5月4日
许可协议