问题
I've just started using AntiXSS (4.3.0), mostly to use @Encoder.JavaScriptEncode as described here.
I installed AntiXSS from Nuget, then added encoderType="Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary" to <httpRuntime in my Web.config.
In my view, I have the following line (within <script> tags):
var userId = @Encoder.JavaScriptEncode(User.Identity.GetUserId());
Which I would expect to output
var userId = 'user-id';
but instead outputs:
var userId = 'user-id';
I assume this is happening because Razor is trying to sanitize the HTML, and thus encoding the singe quotes as '.
The solution then would be to just wrap it in Html.Raw(), but in the post I was following he never does that (instead wrapping the whole thing in single quotes within the Javascript).
My question is - are you supposed to need to call @Html.Raw(Encoder.JavaScriptEncode(data)), or is there something wrong with my setup?
Thanks!
回答1:
Your assumption about razor encoding is correct. I'd also say the post you were following is also correct (I may be wrong, I haven't read the entire post though).
Instead of
var userId = @Encoder.JavaScriptEncode(User.Identity.GetUserId());
try
var userId = '@Encoder.JavaScriptEncode(User.Identity.GetUserId(), emitQuotes: false)';
//optionally surround with '' if your userId needs to be a string
or just
var userId = @Encoder.JavaScriptEncode(User.Identity.GetUserId(), emitQuotes: false);
// Visual Studio gives you a red squiggly syntax error after the semi-colon though.
// From your example, if it is a number, then no quotes are required
or go ahead with Html.Raw() like
var userId = Html.Raw(@Encoder.JavaScriptEncode(User.Identity.GetUserId());
Opionated: I prefer emitQuotes: false because that option is there, and because it eliminates the needs for another function call Html.Raw(). The default for emitQuotes is true. Are you missing the emitQuotes parameter or is that intentional?
来源:https://stackoverflow.com/questions/24856050/antixss-javascriptencode-gets-html-encoded