Display data correctly.
Assuming your web application produces HTML output, you should always
bear in mind that any text you include in that output will also be interpreted
as HTML by your visitors’ browsers. As such, you need to escape special
characters (such as < and &) correctly, using the HttpUtility.HtmlEncode
method.
This is especially important when you’re outputting a string that was originally
received as user input. If that user input were to contain HTML code, that
code might disrupt the appearance or functionality of your application when
it was displayed. For example, if you want to display the text <script> using
a Label control, you should set your label’s Text property to HttpUtil-
ity.HtmlEncode("<script>").
Note that the fields or columns of data-bound controls such as GridView and
DetailsView have a property called HtmlEncode, the default value of which
is True. As such, any values that are displayed by these controls are automat-
ically HTML-encoded unless you set this property to False.
Keep sensitive data to yourself.
Even though it may not be visible in the browser window, any output that
your application produces is ultimately accessible to the end user. Con-
sequently, you should never include sensitive data (such as user passwords,
credit card data, and so on) in JavaScript code, HTML hidden fields, or the
ViewState collection. (Unlike the Application, Session, or Cache collections,
ViewState isn’t stored on the server, but is passed back and forth between
the client and the server on every request in an easily-decipherable format.)
Use encryption or hashing whenever necessary.
ASP.NET offers you the tools to encrypt your data using symmetric algorithms
(which use the same key to encrypt and decrypt the data) or asymmetric
algorithms (which are based on public key/private key pairs).
As we’ll see later in this chapter, ASP.NET also supports hashing, an irrevers-
ible form of encryption that you can use to encrypt passwords and store them
safely on your server.
Use secure communication channels whenever necessary.
You can always use the HTTPS (HTTP Secure) protocol to secure the com-
munication between your visitors and your site. Using this protocol, an atta-
cker who intercepts the data being passed back and forth between your ap-
plication and its users won’t obtain any meaningful data.
529
Basic Security Guidelines