admin管理员组

文章数量:1318153

How can we handle the javascript injection in asp mvc (C#) application?

I can use Html.Encode in my View. But the problem is i have html also to show in the page like a blog post.

I need to remove the script entered in the input elements of the application? How can i do that in a mon place?

How can we handle the javascript injection in asp mvc (C#) application?

I can use Html.Encode in my View. But the problem is i have html also to show in the page like a blog post.

I need to remove the script entered in the input elements of the application? How can i do that in a mon place?

Share Improve this question edited Feb 6, 2010 at 6:00 Prasad asked Feb 6, 2010 at 5:52 PrasadPrasad 59.5k65 gold badges153 silver badges201 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

The "high-level" best practice for doing this is:

  • Store user-input the way it was entered into the system
  • HTML encode all user-input when it is output on any page
  • Use a white-list approach to "de-encode" allowed HTML characters, attributes, attribute values, etc. that you encoded in the previous step

HTML Encoding user-input on output will stop JavaScript from being executed on your site.

The reasons why you want to store user-input "as entered" is because you may in the future decide to output user data in other formats (PDF, email, JavaScript, RSS, etc) that don't have the same rules for encoding. As a result, you should keep data as close to its original form as possible. This will make things easier to deal with later.

For HTML Encoding user-input, you can use System.Web.HttpUtility.HtmlEncode(...).

To bine steps 2 & 3, you can use Microsoft's AntiXSS library. It provides some extra encoding methods that the HttpUtility class doesn't provide to make your job easier. I was unaware until Malcolm pointed out in the ments, that the latest version of this library includes a method called GetSafeHtmlFragment(...) which will remove all JavaScript manually. This will handle all of the heavy lifting of removing user-entered JavaScript code for you. You will most likely want to use GetSafeHtmlFragment and not GetSafeHtml, which is designed to encode entire HTML documents.

Minor note: Read the reviews of the latest AntiXss release (January 2012 at the time of writing this) if you find functionality is not working as you expect. You may want to consider using an older release depending on your needs, though be advised that older releases have known security defects in them. Microsoft has acknowledged the issue and is looking into a solution.

本文标签: handle javascript injection in aspnet mvcStack Overflow