Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  56] [ 6]  / answers: 1 / hits: 18263  / 10 Years ago, fri, march 28, 2014, 12:00:00

I use the Newtonsoft library to convert C# objects into JSON. Is this use of Newtonsoft.Json.JsonConvert.SerializeObject secure, or is additional encoding necessary? If additional encoding is needed, what do you suggest?



Here is how I use it in a Razor view:



<script type=text/javascript>
var jsModel = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))
</script>

More From » asp.net-mvc

 Answers
36

You will at the very least need to perform additional encoding of the '<' character to 'u003C' and the '>' character to 'u003E'. Last I checked JSON.NET did not encode these characters in string literals.



I'm probably going to get flak for this, but the way I would do this is to render a dummy element onto the page:



<div id=the-div [email protected](Model) />


Then, in Javascript, extract the data-json attribute value from the the-div element and JSON.parse it. The benefit to this is that you don't need to worry about which characters require special encoding. The SerializeObject method guarantees that the JSON blob is well-formed, and the @ operator guarantees that any remaining non-HTML-safe characters left over from the JSON conversion are properly escaped before being put into the HTML attribute (as long as the attribute value is surrounded by double quotes, as above). So yes, it's a little uglier, but it is effective at completely shutting down an entire class of vulnerabilities.


[#71721] Thursday, March 27, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wilson

Total Points: 27
Total Questions: 93
Total Answers: 93

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
wilson questions
Tue, Aug 9, 22, 00:00, 2 Years ago
Wed, May 11, 22, 00:00, 2 Years ago
Wed, May 20, 20, 00:00, 4 Years ago
Wed, May 13, 20, 00:00, 4 Years ago
;