Search code examples
html-encodeantixsslibrary

How to handle encoded inputs that need to be edited?


Using Microsoft's AntiXssLibrary, how do you handle input that needs to be edited later?

For example:

User enters: <i>title</i>

Saved to the database as: <i>title</i>

On an edit page, in a text box it displays something like: &lt;i&gt;title&lt;/i&gt; because I've encoded it before displaying in the text box.

User doesn't like that.

Is it ok not to encode when writing to an input control?

Update:

I'm still trying to figure this out. The answers below seem to say to decode the string before displaying, but wouldn't that allow for XSS attacks?

The one user who said that decoding the string in an input field value is ok was downvoted.


Solution

  • Looks like you're encoding it more than once. In ASP.NET, using Microsoft's AntiXss Library you can use the HtmlAttributeEncode method to encode untrusted input:

    <input type="text" value="<%= AntiXss.HtmlAttributeEncode("<i>title</i>") %>" />

    This results in

    <input type="text" value="&#60;i&#62;title&#60;&#47;i&#62;" />
    in the rendered page's markup and is correctly displayed as <i>title</i> in the input box.