Reputation: 1325
I've been reading extensively for the last 2 days about securing ASP.NET applications. However there are contradictory opinions whether html form inputs should be encoded before they are inserted in a SQL database or just before they are sent back to the browser. I think the former opinion makes more sense to me and I will encode all form inputs once they are received by the server and then inserted in the database. However I'm a bit confused about what will happen next!
So let me follow a string from the time it's created until it is sent back to the browser.
Step 1
A user inputs the following string:
string userString = "It's important to know that 1 > 0";
Step 2
Once received by the server the string is encoded and inserted in the database.
string RenderedString = HttpUtility.HtmlEncode(userString);
As a result the string in the database is saved as follows:
"It's important to know that 1 > 0."
Step 3
I want to send the rendered string back to the browser as it is so it will be written on the webpage as html, and not parsed and rendered by the browser. The result will be:
string StringResult = "It's important to know that 1 > 0";
My question is: Should I add any extra "safety" step before sending the string back to the browser or is it enough with the 3 above steps? Any help would be well appreciated?
Upvotes: 0
Views: 1595
Reputation:
Your assumption (that strings stored in the database are only sent back to the browser) is incorrect.
You can do other things with strings, which do not expect them to be HTML-encoded:
Most software assumes strings are unencoded.
MVC automatically HTML-encodes strings before sending them to the browser.
Upvotes: 1
Reputation: 1616
I would always save the data without encoding because I might need to show it in some other form e.g: JSON. Saving it encoded to the database would mean to me that I'm putting the view logic inside my data model.
Upvotes: 1