1

If you need to put valid JavaScript or a URL in to a .NET button's onclick attribute, for example, security scanning software might flag any untrusted data and ask you to encode the value, but you'll end up with invalid JS and/or URL's.

e.g.

This would work, but get flagged by the security scan:

someButton.Attributes["onclick"] = "document.location.href = '" + someUrl + "'; return false;";

This would be a mess of escape chars in the browser:

someButton.Attributes["onclick"] = Microsoft.Security.Application.Encoder.HtmlAttributeEncode("document.location.href = '" + someUrl + "'; return false;");

So would this:

var encodedUrl = Microsoft.Security.Application.Encoder.UrlEncode(someUrl);
var encodedJs = Microsoft.Security.Application.Encoder.JavaScriptEncode(string.Format("document.location.href = '{0}'; return false;", endocdedUrl);
someButton.Attributes["onclick"] = encodedJs;

Based on this thread, I also tried using Page.ClientScript.RegisterStartupScript, but again, anything I send to the browser that has been encoded is invalid.

I suppose I could decode on the client but surely that negates the whole encoding exercise? I must be missing something obvious here?

1 Answer 1

0

If you are encoding something, you have to decode it to be a valid string.
For example, say you have a < symbol in your URL or in javascript. Such symbol without being encoded probably will be flagged as unsafe, so you encode it to &lt;. But this will be clearly not a valid url, and javascript will be broken, if you leave it in that state.

So on the client side you have to decode your string either for url or for javascript. Safiest approach is to construct url on the client inself, doing some concatenation from a parameters coming from server, so you code on server will be like:

using Microsoft.Security.Application;
// ...
someButton.Attributes["onclick"] = Encoder.HtmlAttributeEncode("return runUrl(23412);");

and on the client side the function will be:

var runUrl = function(id) {
  document.location.href = SOME_BASE_URL + '?id=" + id + "';
  return false;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.