• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 62
  • Last Modified:

When can HttpUtility.HtmlEncode() reduce risk of XSS attack?

When can HttpUtility.HtmlEncode() reduce risk of XSS attack?

I was under the impression that it was best practice to encode the URL before I call Redirect().

For example:
                    return Redirect(HttpUtility.HtmlEncode(returnUrl));

But then was told it makes no difference, since encoding it just means the browser needs to decode it. And, all that matters is how you protect yourself from incoming malicious URL's. Obviously, a hacker can reformat any outputted URL.

Where and when does it make sense to use HttpUtility.HtmlEncode(returnUrl) ?

2 Solutions
Shaun VermaakTechnical Specialist/DeveloperCommented:
Are you not confusing HttpUtility.HtmlEncode and HttpUtility.URLEncode?

HttpUtility.HtmlEncode would prevent XSS when attacker saves malicious HTML/JS etc. content in a form and you display is later in a process
You should HttpUtility.HtmlEncode(returnUrl) anytime you need to display it on the page, for example in the exceptions/errors page. However, if the returnUrl is generated on the server side or is validated such that

1- its a proper URL
2- Its relative URL or to a trusted domain

then you may skip the encoding. Again, it is unlikely that you'd need to display the return URL.

HtmlEncode is unnecessary when doing a Redirect. You may need URLEncode if you are appending query params to the returnUrl, for example.
newbiewebSr. Software EngineerAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The Firewall Audit Checklist

Preparing for a firewall audit today is almost impossible.
AlgoSec, together with some of the largest global organizations and auditors, has created a checklist to follow when preparing for your firewall audit. Simplify risk mitigation while staying compliant all of the time!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now