简体   繁体   English

服务器端JSON字符串验证

[英]Server side JSON string validation

Is there a secure way to validate an incoming untrusted JSON string in php? 有没有一种安全的方法来验证php中传入的不受信任的JSON字符串?

The client shows a dynamic form. 客户端显示动态表格。 The user can enter data into that form. 用户可以将数据输入该表格。 The data needs to be saved on the server. 数据需要保存在服务器上。 The server will not work with the data, it will only pass it on to the client the next time the page is loaded in order to restore the forms values. 服务器将无法使用数据,它将仅在下次加载页面时将其传递给客户端,以还原表单值。 Therefore I do not want to check every value separately and save it into its own database field. 因此,我不想单独检查每一个值,并将其保存到自己的数据库字段。

I want to save it as a JSON string and insert it into the DOM as a object variable on every page load. 我想将其保存为JSON字符串,并在每次页面加载时将其作为对象变量插入到DOM中。 Is there a secure way to sanitize the incoming JSON string for that? 有没有一种安全的方法可以为此清理传入的JSON字符串?

If you're injecting the code into a script tag and you want to guarantee that it is pure Javascript code, without any potentially dangerous XSS vulnerabilities, the simple way would be to use PHP first to decode it and then to re-encode it. 如果要将代码注入到script标签中,并且要保证它是纯Javascript代码,没有任何潜在的危险XSS漏洞,则简单的方法是首先使用PHP对其进行解码,然后对其进行重新编码。

$safeJSON = json_encode(json_decode($unsafeJSON));

Anything that is invalid JSON will return null when json_decode is called on it. 无效的JSON会在json_decode时返回null In this case, the string "null" would be returned to your browser, which is unlikely to do any harm in this context! 在这种情况下,字符串"null"将返回到您的浏览器,在这种情况下这不太可能造成任何损害!


It's worth noting, however, that what you are doing is only potentially unsafe because this is not actually JSON. 值得注意的是,您所做的只是潜在的不安全,因为它实际上不是JSON。 When it's being used inside a script tag, it's simply a Javascript object literal. script标记内使用它时,它只是Javascript对象文字。 If you were using it as JSON, eg by doing an AJAX call, it would not be a security vulnerability because the browser will not recognise invalid JSON in a JSON.parse call. 如果您将其用作JSON(例如通过进行AJAX调用),则不会造成安全漏洞,因为浏览器无法识别JSON.parse调用中的无效JSON。 See this excellent blog post for more information on the difference between Javascript objects and JSON. 有关Javascript对象和JSON之间的区别的更多信息,请参见这篇出色的博客文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM