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>
Return ValueA JSON string representation of the object.
SerializeObject Method. Serializes the specified object to a JSON string. Serializes the specified object to a JSON string using formatting.
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With