开发者

How to handle Html inputs in the TextBox

I have a requirement that user can input HTML tags in the ASP.NET TextBox. The value of the textbox will be saved in the database and then we need to show it on some other page what he had entered. SO to do so I set the ValidateRequest="false" on the Page directive. Now the problem 开发者_运维问答is that when user input somthing like :

<script> window.location = 'http://www.xyz.com'; </script>

Now its values saved in the database, but when I am showing its value in some other page It redirects me to "http://www.xyz.com" which is obvious as the javascript catches it. But I need to find a solution as I need to show exactly what he had entered. I am thinking of Server.HtmlEncode. Can you guide me to a direction for my requirement


Always always always encode the input from the user and then and only then persist in your database. You can achieve this easily by doing

Server.HtmlEncode(userinput) 

Now, when it come time to display the content to the user decode the user input and put it on the screen:

Server.HtmlDecode(userinput)


You need to encode all of the input before you output it back to the user and you could consider implementing a whitelist based approach to what kind of HTML you allow a user to submit.

I suggest a whitelist approach because it's much easier to write rules to allow p,br,em,strong,a (for example) rather than to try and identify every kind of malicious input and blacklist them.

Possibly consider using something like MarkDown (as used on StackOverflow) instead of allowing plain HTML?


You need to escape some characters during generating the HTML: '<' -> &lt;, '>' -> &gt;, '&' -> &amp;. This way you get displayed exactly what the user entered, otherwise the HTML parser would possibly recognize HTML tags and execute them.


Have you tried using HTMLEncode on all of your inputs? I personally use the Telerik RadEditor that escapes the characters before submitting them... that way the system doesn't barf on exceptions.

Here's an SO question along the same lines.


You should have a look at the HTML tags you do not want to support because of vulnerabilities as the one you described, such as

  • script

  • img

  • iframe

  • applet

  • object

  • embed

  • form, button, input

and replace the leading "<" by "& lt;".

Also replace < /body> and < /html>

HTML editors such as CKEditor allow you to require well-formed XHTML, and define tags to be excluded from input.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜