Cross Site Scripting Vulnerability

Overview

Cross-Site Scripting Vulnerability, or XSS for short. Scripts in Web sites return user input (usually parameter values) without pre-sanitization, and the browser executes the JavaScript code entered by the user when it is returned in the response page. Attackers often use this principle to insert malicious code into web pages and generate malicious links to induce users to click. When the user clicks on the link, a request to the Web site is generated with a parameter value containing malicious JavaScript code. If the Web site embeds this parameter value in the response HTML page (which is the essence of the site's problem), malicious code will run in the user's browser, allowing the attacker to achieve its goal. For websites with XSS vulnerabilities, it is recommended to filter the content entered by the user and check whether there is any illegal content in the content entered by the user. Such as <> (angle brackets), (" quotation marks), ' (single quotation marks), % (percent sign), ; (semicolon), () (brackets), &, + (plus sign), etc. and strictly control the output.

solution

In Spring MVC, all Controllers can inherit the BaseController.

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

/**
 * 控制器支持类
 */
public abstract class BaseController {
	
	/**
	 * 初始化数据绑定
	 * 1. 将所有传递进来的String进行HTML编码,防止XSS攻击
	 */
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// String类型转换,将所有传递进来的String进行HTML编码,防止XSS攻击
		binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
			}
			@Override
			public String getAsText() {
				Object value = getValue();
				return value != null ? value.toString() : "";
			}
		});
	}
	
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324982188&siteId=291194637