How to create secure web applications in ASP.NET

You should always keep the following guidelines in mind when writing code in terms of web applications:

Never trust user input – Assume that every user is evil, until you have confirmed the opposite. You should always strongly validate user input. Write your validation code in a way that it verifies input against only allowed values and not invalid values.

Never use string concatenation for creating SQL statements – Always use parametrized statements so that your application is not SQL injectable.

Never output data entered by a user directly on your web page before validating and encoding it – When user enters some HTML code fragments (e.g. scripts) that lead to cross-site scripting vulnerabilities. For that reason, always use HttpUtility.HtmlEncode() for escaping special characters such as < or > before outputting them on the page, or use a web control that performs this encoding automatically.

Never store sensitive data, business-critical data, or data that affects internal business rule conclusions made by your Web application in hidden fields on your page – Hidden fields can be changed easily by just viewing the source of the web page, modifying it, and saving it to a file. Then an attacker simply needs to submit the locally saved, modified web page to the server. Available browser plug-ins make this approach as easy as writing an e-mail with popular mail clients.

Never store sensitive data or business-critical data in view state – View state is just another hidden field on the page, and it can be decoded and viewed easily. View state encryption protects information for a limited interval of time. You should keep in mind that even encrypted data can eventually be cracked if an attacker has enough time, resources, and motivation.

Enable SSL when using Basic authentication or ASP.NET forms authentication or use SSL – If your web application processes sensitive data you should secure your whole website using SSL. You should protect also image directories or directories with other files not managed by the application directly through SSL.

Protect your cookies – Always protect your authentication cookies when using forms authentication, and set timeouts as short as possible and only as long as necessary.