Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the output of JsonConvert.SerializeObject need to be encoded in Razor view?

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>
like image 666
Jeremy Cook Avatar asked Mar 28 '14 20:03

Jeremy Cook


People also ask

What does JsonConvert SerializeObject return?

Return ValueA JSON string representation of the object.

How does JsonConvert SerializeObject work?

SerializeObject Method. Serializes the specified object to a JSON string. Serializes the specified object to a JSON string using formatting.

What is JsonConvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

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" data-json="@JsonConvert.SerializeObject(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.

like image 53
Levi Avatar answered Sep 18 '22 14:09

Levi