I want to display user content in a java script variable.
As with all user generated content, I want to sanitize it before outputting.
ASP.Net MVC does a great job of this by default:
@{
var name = "Jón";
}
<script> var name ='@name';</script>
The output for the above is:
Jón
This is great as it protects me from users putting <tags>
and <script>evilStuff</script>
in their names and playing silly games.
In the above example,I want sanity from evil doers but I don't want to HTML encode UTF8 valid characters that aren't evil.
I want the output to read:
Jón
but I also want the XSS protection that encoding gives me.
Outside of using a white listing framework (ie Microsoft.AntiXSS) is there any built in MVC function that helps here?
UPDATE:
It looks like this appears to achieve something that looks like it does the job:
@{
var name = "Jón";
}
<script> var name ='@Html.Raw(HttpUtility.JavaScriptStringEncode(name))';
Will this protect against most all XSS attacks?