Search code examples
c#.netjsonjson.net

Json.NET SerializeObject escape values to prevent XSS


Using Json.NET

JsonConvert.SerializeObject(new { Property = "<script>alert('o hai');</script>" })

returns

{"Property":"<script>alert('o hai');</script>"}

Is it possible for the value to be escaped by SerializeObject to prevent a hostile script from executing? I'd prefer not to make changes to the object itself.

Edit: Ideally I'd like to integrate the sanitizing into the SerializeObject call without having to process the object before or after SerializeObject.

Edit: The string output from JsonConvert.SerializeObject is assigned to a global variable in a script block, which I believe is where the XSS issue is.


Solution

  • Functionality to achieve this was added in version 4.5.11

    This allows you to add various type of escaping to the output.

    This is my LinqPad test:

        var settings = new JsonSerializerSettings();
    
        settings.StringEscapeHandling = StringEscapeHandling.EscapeHtml;
    
        var output = JsonConvert.SerializeObject(new { Property = "<script>alert('o hai');</script>" }, settings);
    
        Debug.Print(output);
    

    outputs

    {"Property":"\u003cscript\u003ealert(\u0027o hai\u0027);\u003c/script\u003e"}
    

    Just as a disclaimer, this isn't a golden bullet to fix xss, but should help you mitigate it a bit given your example.