Preventing Anonymous Access to Web Sites in ASP.Net


Introduction

By default in an ASP.NET Web site, visitors can browse the site anonymously, load pages, and download the content we provide. They do not have to provide any credentials for example, by logging in to the site. For most Web sites, of course, this is just what we want. However, there are occasions, depending on the type of content we provide, when we want to force users to identify themselves before they access the content. This might be as soon as they arrive at the site, or it might be at some point such as a checkout, when they are buying goods, or just so that we can allocate forum posts this visitor makes to them like c-sharpcorner.com web portal.

Configuration Files

Most of the default configuration settings for ASP.NET web sites we create are in the web.config and machine.config files stored in the folder C\Windows\Microsoft.NET\Framework\v[version]\CONFIG\ of your PC. We can override most of these settings simply by placing a web.config file in the folders of your site or application. Visual Studio 2005 and Visual Web Developer can automatically create these files to enable debugging of pages as we build your site.
The <system.web> section of the web.config file can contain a section named <authorization> that controls access to the site and to individual subfolders with the site's virtual root. If there is no <authorization> in the local or default web.config file, the equivalent section in the configuration file for the machine, machine.config, provides the settings.

<system.web>
  ...
  <authorization>
    <allow users="*" />
  </authorization>
  ....
</system.web>


ASP.NET Authentication and Authorization

Once ASP.NET starts to process the request received from IIS, it does so using its own configuration and security settings. These are wholly contained in the machine.config file and more specifically the various web.config files in the root and subfolders of your Web site and application directories.
These are the settings the ASP.NET Web Administration Tool is specifically designed to manage.

ASP.NET Authentication Settings

The <authentication> element can appear in a web.config file in the root of your Web site or a virtual application root folder. It specifies the type of authentication ASP.NET uses, the specific settings for this authentication process and, optionally, the accounts that have access to ASP.NET resources.

<system.web>
...
<authentication mode="Windows|Forms|Passport|None">
<forms name="name"
path="/"
domain="domain name"
loginUrl="url"
defaultUrl="url"
protection="All|None|Encryption|Validation"
timeout="30"
slidingExpiration="true|false"
requireSSL="true|false"
cookieless="UseCookie|UseUri|UseDeviceProfile|AutoDetect"
enableCrossAppRedirects="[true|false]">
<credentials passwordFormat="Clear|SHA1|MD5">
<user name="username" password="password"/>
</credentials>
</forms>
<passport redirectUrl="internal"/>
</authentication>
...
</system.web>


The mode attribute specifies the type of authentication process. The three types are:

  • Windows. In this mode, ASP.NET authenticates users against the list of Windows accounts and groups specified for the machine or the domain within which the machine resides. When using this type of authentication, we do not include the <forms> or <passport> elements within your <authentication> element. Windows authentication is ideal for intranet usage, where users can authenticate in IIS using their Windows logon credentials.

  • Forms. In this mode, ASP.NET stores a cookie on the user's machine that contains encoded authentication information. If this cookie is not present, for example, when they first visit the site, ASP.NET redirects them to a login page where they provide their username and password. The <forms> element, described in more detail in the next section, specifies the parameters and, optionally, the login credentials applied. When using this type of authentication, we do not include the <passport> element within your <authentication> element.
     
  • Passport. In this mode, ASP.NET redirects users to the Microsoft Passport Web site where they enter their login credentials for authentication. The Passport site then redirects them to your site after placing a suitable cookie on their machine that identifies them. The <passport> element defines the URL for the Passport site, and we must sign up with Microsoft Passport (and pay a fee) to use this service. When using this type of authentication, we do not include the <forms> element within your <authentication> element.
Using Forms Authentication

The most common authentication approach for public Web sites and Web applications is Forms authentication. This does not rely on any specific network protocols and works through firewalls and proxy servers as well as over the Internet. It is, in fact, similar to the custom techniques that Web site developers have used for many years. However, ASP.NET makes it easy to program and, in most cases, a lot more secure than customer techniques.

The <forms> element contains the following series of attributes that define the behavior of the authentication process:
  • name. This attribute defines the name of your application and identifies the cookie sent to the client. The default, if omitted, is .ASPXAUTH. If we run multiple applications on the same machine, we should provide each one with a unique name.
  •  
  • path. This attribute defines the path to which the authentication cookie applies. In general, we will use "/" so that it applies to the complete site. This avoids issues such as repeated login redirects as users navigate different sections of the site.
     
  • domain. This optional attribute can be used to change the name of the domain in the authentication cookie.
     
  • loginUrl. This attribute specifies the URL of the login page where ASP.NET redirects visitors who do not have a valid cookie present.
     
  • defaultUrl. This optional attribute specifies the URL that the Forms authentication system will redirect the user to once authentication is complete. The default value if omitted is "default.aspx".
     
  • protection. This attribute defines if ASP.NET will apply encryption and/or validation to the cookie. The validation algorithm uses the value of the <machineKey> element in machine.config. The encryption method is Triple-DES (3DES) if available and the key 48 bytes or more, or DES otherwise. We should generally specify All for maximum security.
     
  • timeout and slidingExpiration. This attribute defines the number of minutes before the cookie expires, and hence the user has to log in again. Each page request resets the timer by creating a new cookie, unless we set the slidingExpiration attribute to true. The default for the slidingExpiration attribute is false.
     
  • requiresSSL. This attribute specifies if requests to the login page (defined in the loginUrl attribute) must be over a secure connection using SSL. We should endeavor to always use SSL for your login pages, with the possible exception of applications where security is non-critical (such as when used only for page personalization).
     
  • cookieless. This attribute specifies if cookies are used to maintain authentication between requests, or if the information should be encoded into the URL. The "AutoDetect" setting causes ASP.NET to use cookies where the browser supports them and they are enabled. The "UseDeviceProfile" setting specifies that ASP.NET should use cookies whenever the browser information stored in the browser capabilities files suggests that cookies are supported, without checking if the user has disabled them.
     
  • enableCrossAppRedirects. This optional attribute, when set to "true", allows code to redirect users to different ASP.NET applications while preserving the authentication state. In this case, we must specify the same name, protection, and path attribute values in both applications and the same specific keys for the <machineKey> sections of the web.config files.
The <credentials> Element

Both Windows and Passport authentication techniques maintain a list of valid users, outside of your ASP.NET application. Windows stores its accounts details in an internal secure database on the server or the domain controller. The Microsoft Passport site stores user details centrally, and it does not expose them to your ASP.NET applications.
However, when we use Forms authentication, we must provide the list of valid users so that ASP.NET can validate logon requests. One way is to include the list of users in your web.config file in the <credentials> element. For each user, we include a <user> element that specifies the user name and password. To avoid storing plain text passwords, we can encrypt them using the delightfully named HashPasswordForStoringInConfigFile method of the System.Web.Security.FormsAuthentication class. We then specify the encryption type we used in the passwordFormat attribute of the <credentials> element.

Cookie-less Sessions and Cookie-less Forms Authentication

One issue that we might come across when using Forms authentication is that it depends on the client's browser accepting and then returning the special cookie that indicates they were authenticated. For clients that do not support cookies, or who have disabled them in their browser options, Forms authentication (together with session support and other features of ASP.NET) will fail to work correctly, because ASP.NET cannot then recognize users when they make a subsequent request.
To get around this, we can use cookie-less sessions and cookie-less Forms authentication methods. When we enable cookie-less sessions, ASP.NET inserts the session ID into the URL so that it recognizes the user on the next request. The <sessionState> element in the <system.web> section of web.config can specify that ASP.NET should use cookie-less sessions:

<sessionState cookieless="true" />

We specify cookie-less Forms authentication using the cookieless attribute of the <forms> element, as shown at the beginning of this current section. The FormsAuthentication class exposes the static CookiesSupported and CookieMode properties that provide information about the current configuration or the current user's cookie support.

ASP.NET Authorization Settings

Having specified the type of authentication we will use, we now have a technique that allows ASP.NET to identify visitors to the site, or to a specific subsection of the site. However, we also have to provide ASP.NET with information on what permissions and privileges each user should have. In other words, having identified a user, should ASP.NET allow that user to access a specific folder or resource?

<system.web>
...
<authorization>
<allow users="comma-separated list of users"
roles="comma-separated list of roles"
verbs="comma-separated list of verbs"/>

<deny users="comma-separated list of users"
roles="comma-separated list of roles"
verbs="comma-separated list of verbs"/>
</authorization>
...
</system.web>


There are two specific characters we can use in the users attribute of the <allow> and <deny> elements:

• The asterisk (*) means "all users"
• The question mark (?) means "anonymous users," in other words, users that have been authenticated by IIS within the context of the "IUSR_[machine-name]" account

The verbs attribute refers to specific types of HTTP request; the types recognized by ASP.NET are GET, HEAD, POST, and DEBUG. This means that we can allow or deny access based on the type of request. For example, we can allow specific users (or all users) to access pages only by using values in the query string (GET) and not when posting values from a <form>.

The most stringent rules take precedence, so that (when using Windows authentication) we can deny access to a Windows account group in the <deny> element but then allow access to a specific account within that group using the <allow> element.
We use the <authorization> element in a web.config file placed in the secured target folder of your site in other words, in the folder(s) where we want to limit access to specific authenticated users. These folders must be within the virtual application to which the <authentication> element applies. Alternatively, we can use the <location> element to target parts of a web.config file at a specific folder or resource, as shown in example

<configuration>
...
<system.web>
...
<authentication mode="Forms">
<forms name="myapp" path="/" loginUrl="login.aspx"
protection="All" requireSSL="true"
timeout="30" slidingExpiration=" false">
<credentials passwordFormat="Clear|SHA1|MD5">
<user name="alex" password="56&FEw%x2K"/>
</credentials>
</forms>
</authentication>
...
</system.web>
<location path="SecureArea"
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
...
</configuration>


HAVE A HAPPY CODING!
 


Similar Articles