Question

I need to encode some javascript on the server side that is getting injected into the html. I'm using Microsoft.Security.Application.Encoder.JavaScriptEncode() but it ends up looking like this from view source:

'var DesignTheme \x3d \x7b\x22StyleId\x22\x3a\x2235\x22,\x22BackgroundColor\x22\x3a\x22\x23DDF1FA\x22,\x22HeaderColor\x22\x3a\x22\x230B70A6\x22,\x22ButtonColor\x22\x3a\x22\x2347B937\x22,\x22BoxBackgroundColor\x22\x3a....

What gives? Am I using the wrong method to encode? The goal is to prevent cross site scripting, and this javascript threw a red flag on a recent security scan of our website.

Was it helpful?

Solution

Microsoft.Security.Application.Encoder.JavaScriptEncode() is only intended to encode untrusted data that will be used in a JavaScript string literal. The optional second argument, boolean emitQuotes, specifies whether quotation marks will be added at either end the output string (the default is true). So for example, here are two ways the method might be used in ASP.NET WebForms:

<script>
    <% string nameEnteredByUser = "alert('I am a hacker');"; %>

    var name = <%= Microsoft.Security.Application.Encoder
        .JavaScriptEncode(nameEnteredByUser) %>;
    var nameWithMessage = '<%= Microsoft.Security.Application.Encoder
        .JavaScriptEncode(nameEnteredByUser, false) %>' + ' is a very nice name.';

    console.log(name); //alert('I am a hacker');
    console.log(nameWithMessage); //alert('I am a hacker'); is a very nice name.

</script>

OTHER TIPS

Maybe you are looking for one of the encodes in System.Web.HttpUtility?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top