AntiXSS JavaScriptEncode gets HTML encoded?

时间秒杀一切 提交于 2021-01-28 05:30:12

问题


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 = &#39;user-id&#39;;

I assume this is happening because Razor is trying to sanitize the HTML, and thus encoding the singe quotes as &#39;.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!