Securing individual pages

Learning Resources

Securing individual pages

ASP.Net has a built-in feature named Forms Authentication that allows a developer to easily secure certain areas of a web site. In this post I’m going to build a simple authentication sample using C# and ASP.Net 4.0.

The security settings with ASP.Net are configured from within the web.config file. This is a standard ASCII file, with an XML format, that is located in the root of your web application. Here is a sample web.config file:






The very first line is standard for a web.config file and has no bearing on the security.

The next section specifies that you are configuring the security for this web application. First we set the authentication mode to use a cookie in this specific example. You can specify a unique name for your cookie. This section also specifies the page or URL that will contain the authentication code (login.aspx in this case) and how long the authentication cookie should be persisted.

The next two lines specify valid usernames and passwords for this web application. As far as I know there is no limit to the number of user accounts you can place in the web.config, but if there were a large number – or if they change frequently – it might be better to place this information in an external file like a database or an XML file instead (I’ll show this in a future article).

Now that we have specified some valid logon accounts, we need to actually specify that we want to password protect. For this example I have decided to password protect the entire web site starting at the root, so the optional attribute will not be used. We set the authorization to deny all non-authenticated users (deny users=”?”).

That’s all that is needed for the config.web file.

 For Support