由于JSON.parse()
不会在要解析的数据中运行任何代码,因此它不像eval()
那样容易受到攻击,但仍然需要采取一些措施来保护服务器和应用程序的完整性,例如:
- Apply exception handlers in the appropriate place as
JSON.parse()
can throw an exception.
- 不要假设那里有什么数据,在使用之前必须明确测试数据.
- Only process properties you are specifically looking for (avoiding other things that might be in the JSON).
- Validate all incoming data as legitimate, acceptable values.
- Sanitize the length of data (to prevent DOS issues with overly large data).
- 不要将这些传入的数据放在可以对其进行进一步判断的地方,例如直接放在页面的HTML中,或直接注入SQL语句中,而无需进一步消毒以确保其在该环境中是安全的.
因此,要直接回答您的问题,除了使用正文解析器之外,还有更多的事情要做,尽管它是第一次处理数据的非常好的前线.从正文解析器获得数据后,接下来的处理步骤在很多情况下都很重要,可能需要格外小心.
As an example, here's a parsing function that expects an object with properties that applies some of these checks and gives you a filtered result that only contains the properties you were expecting:
// pass expected list of properties and optional maxLen
// returns obj or null
function safeJSONParse(str, propArray, maxLen) {
var parsedObj, safeObj = {};
try {
if (maxLen && str.length > maxLen) {
return null;
} else {
parsedObj = JSON.parse(str);
if (typeof parsedObj !== "object" || Array.isArray(parsedObj)) {
safeObj = parseObj;
} else {
// copy only expected properties to the safeObj
propArray.forEach(function(prop) {
if (parsedObj.hasOwnProperty(prop)) {
safeObj[prop] = parseObj[prop];
}
});
}
return safeObj;
}
} catch(e) {
return null;
}
}