1

I want to prevent xss in my application. I have an text input for which I should be able to accept for example <script>alert(1)</script> but as I save this, if I encode it using : System.Web.HttpUtility.HtmlEncode(Me.txtUsername.Text)

I will be able to save the encoded version of this string:

&lt;script&gt;alert(1)&lt;/script&gt;

how should I show this later on without letting the script be executed? if I decode it the script will be executed. I want to later on show this as <script>alert(1)</script>

  • please add a tag indicating which web technology you are using. – Sam Axe Feb 14 '15 at 06:23
  • possible duplicate of [Why does HTML encoding prevent certain XSS attacks?](http://stackoverflow.com/questions/8475306/why-does-html-encoding-prevent-certain-xss-attacks) – CoderDennis Feb 14 '15 at 06:24

2 Answers2

1

Just show the text. Don't decode it. Let the browser do that for you.

<script>alert(1)</script>

See also this answer regarding other types of XSS vulnerabilities that html encoding doesn't protect you from: https://stackoverflow.com/a/70222/69527

Community
  • 1
  • 1
CoderDennis
  • 13,642
  • 9
  • 69
  • 105
  • Hi Dennis, somehow it stays in html form and does not get decoded. I am using chrome. –  Feb 14 '15 at 06:30
  • Maybe you could include more info in your question about how you are displaying the text. – CoderDennis Feb 14 '15 at 06:50
  • I am storing the string using HtmlEncode and then retrieve the encoded string and display it on another page but the string is not being decoded. –  Feb 14 '15 at 07:25
  • Right. I was hoping you would share details of *how* you're displaying it since you're having trouble with that part. – CoderDennis Feb 14 '15 at 17:15
0

If your text is not being decoded you may use jQuery

$("<div/>").html(yourString).text();

Afflatus
  • 933
  • 1
  • 12
  • 39