Understanding the Web Configuration File - Part 1
 
Published: 31 Mar 2005
Unedited - Community Contributed
Abstract
Many of the configuration settings for your ASP.NET application can be maintained in a distinct XML-based text file named Web.config. If you are familiar with XML then you will discover that this file is easy to follow and understand. Even if your experience with XML is limited, I believe you will find the Web.config a friendly configuration alternative.
by Steven Swafford
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 58662/ 38

Introduction

[ Download Code ]

This article will be completed in an ongoing multi-part series, one article per element, with the exception being the authorization and authentication elements which are covered together in this article.

Recommended Software

Prerequisite

This article is intended for the novice ASP.NET developer who may or may not be familiar with utilizing the Web Configuration file. The reader should have a basic understanding of the XML markup language, and be familiar with C# or VB.NET to follow the provided example code. All the screenshots and references to the IDE are of Visual Studio .NET.

Interesting Tid-Bits

  • A Web application can contain more than one Web.config file. The settings in a file apply to the directory in which it's located, and all child directories. Web.config files in child directories take precedence over the settings that are specified in parent directories.
  • Web.config files are protected by IIS, so your user cannot simply browse to them. If you try to retrieve an existing http://somedomain.com/Web.config file, an "Access denied" error message will be shown.
  • There's no need to restart the Web server after you modify a Web.config file. When a change occurs this is detected by ASP.NET on the next request, and the application is reloaded.
Your First Web Configuration File

[ Download Code ]

The first thing you should be familiar with is the default structure of the Web.config file. The following example is generated by Visual Studio .NET when you choose to add a new Web configuration file. [ view screenshot ]

Listing 1: Sample Web.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <compilation defaultLanguage="c#" debug="true" />
    <customErrors mode="RemoteOnly" />
    <authentication mode="Windows" />
    
    <authorization>
      <allow users="*" /> <!-- Allow all users -->
    </authorization>
    
    <trace
      enabled="false"
      requestLimit="10"
      pageOutput="false"
      traceMode="SortByTime"
      localOnly="true" />


    <sessionState
      mode="InProc"
      stateConnectionString="tcpip=127.0.0.1:42424"
      sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
      cookieless="false"
      timeout="20" />


    <globalization
      requestEncoding="utf-8"
      responseEncoding="utf-8" />


  </system.web>
</configuration>

If you are not familiar with creating a Web.config file, simply follow these steps.

  1. From the File menu, select New, and then Blank Solution. [ view screenshot ]
  2. Now that you have a Blank Solution the next step is to add a new Project. [ view screenshot ]
  3. In this case I am adding a VB.NET Project, and then selecting an ASP.NET Web Application choice. [ view screenshot ]
  4. Once your new Project has been established, you should see a screen similar to the following [ view screenshot ]. Notice that Visual Studio .NET has created a Web.config file. This default configuration file will have the settings shown in Listing 1.
  5. If you want to create additional Web configuration files within any folders you have created within this project, right-click the folder in the Solution Explorer, and select Add, Add New Item, and Web Configuration File. [ view screenshot ]

Now that you have been provided with two methods of establishing a Web configuration file, it is time to move on to breaking this file down into greater details.

Web Configuration File Breakdown

[ Download Code ]

I suggest that you take the time to read more on ASP.NET Settings Schema as time permits. This will provide a greater insight into the possibilities of application configuration within .NET.

The root element of every Web configuration file is <configuration>. Within the <configuration> element you may have a total of nineteen possible child elements, which I will further discuss and provide code samples.

Table 1: System.Web Web Configuration File Child Elements

ELEMENT

DESCRIPTION

<authentication>

Configures ASP.NET authentication support. This element can be declared only at the machine, site, or application level. Any attempt to declare it in a configuration file at the subdirectory or page level will result in a parser error message.

<authorization>

Configures ASP.NET authorization support. The <authorization> tag controls client access to URL resources. This element can be declared at any level (machine, site, application, subdirectory, or page).

<browserCaps>

Controls the settings of the browser capabilities component. The <browserCaps> element can be declared at the machine, site, application, and subdirectory level. The <browserCaps> element can be updated as required to detect future browsers and browser capabilities.

<clientTarget>

Adds aliases for specific user agents to an internal collection of user agent aliases.

<compilation>

Configures all the compilation settings that ASP.NET uses.

<customErrors>

Provides information about custom error messages for an ASP.NET application.

<globalization>

Configures the globalization settings of an application.

<httpHandlers>

Maps incoming requests to the appropriate IHttpHandler or IHttpHandlerFactory class, according to the URL and the HTTP verb specified in the request.

<httpModules>

Configures the HTTP modules within an application.

<httpRuntime>

Configures ASP.NET HTTP runtime settings. This section can be declared at the machine, site, application, and subdirectory levels.

<identity>

Controls the application identity of the Web application. This element can be declared at any level (machine, site, application, subdirectory, or page).

<machineKey>

Configures keys to use for encryption and decryption of forms authentication cookie data and view state data, and for verification of out-of-process session state identification. This section can be declared at the machine, site, and application levels, but not at the subdirectory level.

<pages>

Identifies page-specific configuration settings. The <pages> section can be declared at the machine, site, application, and subdirectory levels.

<processModel>

Configures the ASP.NET process model settings on a Microsoft Internet Information Services (IIS) Web server. The <processModel> section can be set only within the Machine.config file and affects all ASP.NET applications running on the server.

<securityPolicy>

Defines valid mappings of named security levels to policy files. This section can be declared at the machine, site, and application levels. You can extend the security system by providing your own named <trustLevel> subtag mapped to a file specified by the policyFile attribute.

<sessionState>

Configures session state settings for the current application.

<trace>

Configures the ASP.NET trace service.

<trust>

Configures the code access security level applied to an application. The <trust> section can be declared at the machine, site, and application levels.

<webServices>

Controls the settings of XML Web services created using ASP.NET.

Authentication and Authorization Example

[ Download Code ]

I will discuss authentication and authorization simultaneously because these elements work together. There are four types of authentication that are available:

  • Windows (which is the default)
  • Forms
  • Passport
  • None

I will provide a sample using Forms authentication. (Be sure to read the Pros and Cons at MSDN.)

Listing 2: Example Authentication and Authorization Elements

<authentication mode="Forms">
<forms name="login" loginUrl="login.aspx" />
</authentication>


<authorization>
<allow roles="author" />
<allow roles="editor" />
<allow users="reader" />
<deny users="*" />
</authorization>

The next step is to add the appropriate code in the Global.aspx file which will handle the application authentication. The default Global.aspx (VB.NET) will look like the following.

Listing 3: Default VB.NET Global.aspx

Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires upon attempting to authenticate the use
End Sub

All you need to do is replace the above default routine with the following. Take notice of the two imports as well.

Listing 4: Modified VB.NET Global.aspx

Imports System.Security.Principal
Imports System.Web.Security


Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires upon attempting to authenticate the use


If Not (HttpContext.Current.User Is Nothing) Then
  If HttpContext.Current.User.Identity.IsAuthenticated Then
    If TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then


  Dim formsIdent As FormsIdentity = CType(HttpContext.Current.User.Identity, FormsIdentity)
  Dim formsAuthTicket As FormsAuthenticationTicket = formsIdent.Ticket
  Dim astrRoles As String() = formsAuthTicket.UserData.Split("|"c)
  HttpContext.Current.User = New GenericPrincipal(formsIdent, astrRoles)


    End If
  End If
End If
End Sub

If you are using C# then use the following method.

Listing 5: Modified C# Global.aspx

using System.Security.Principal;
using System.Web.Security;


protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
//Fires upon attempting to authenticate the use
if (!(HttpContext.Current.User == null))
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity.GetType() == typeof(FormsIdentity))
{
FormsIdentity formsIdent = (FormsIdentity) HttpContext.Current.User.Identity;
FormsAuthenticationTicket formsAuthTicket = formsIdent.Ticket;
String[] astrRoles = formsAuthTicket.UserData.Split('|');
HttpContext.Current.User = new GenericPrincipal(formsIdent, astrRoles);
}
}
}
}

I am not going to cover the details of what is happening with the Global.aspx. Later in the article I will provide a variety of resources that will assist you further.

Creating Login and Logout Pages

[ Download Code ]

Create a login.aspx web page.

This Web Form has three controls which are a TextBox, Button, and Label. [ view screenshot ]

The work happens in the code-behind. There are two functions and one sub routine that we will look at. First is a sub routine to handle the click event of the Login button which in turn implements two functions named ValidateUser and AssignRoles. In a real world environment you may prefer utilizing a database to store user names as well as roles. For the purpose of these examples I have hard coded the roles, username, and password.

Listing 12: btnLogin_Click VB.NET Example

Private Sub btnLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnLogin.Click


If ValidateUser(txtUsername.Text, txtPassword.Text) Then
FormsAuthentication.Initialize()


Dim strRole As String = AssignRoles(txtUsername.Text)
'The AddMinutes determines how long the user will be logged in after leaving
'the site if he doesn't log off.


Dim formsAuthTicket As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
txtUsername.Text, DateTime.Now, _
DateTime.Now.AddMinutes(30), False, strRole, _
FormsAuthentication.FormsCookiePath)


Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, _
FormsAuthentication.Encrypt(formsAuthTicket)))


Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, False))


Else
lblError.Visible = True
End If


End Sub

Listing 13: btnLogin_Click C# Example

private void btnLogin_Click(object sender, System.EventArgs e)
{
if (ValidateUser(txtUsername.Text, txtPassword.Text))
{
FormsAuthentication.Initialize();
String strRole = AssignRoles(txtUsername.Text);
//The AddMinutes determines how long the user will be logged in after leaving
//the site if he doesn't log off.


FormsAuthenticationTicket formsAuthTicket = new FormsAuthenticationTicket(1, 
txtUsername.Text, DateTime.Now, 
DateTime.Now.AddMinutes(30), false, strRole, 
FormsAuthentication.FormsCookiePath);


Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, 
FormsAuthentication.Encrypt(formsAuthTicket)));


Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
}
else
lblError.Visible = true;
}

Listing 14: Validate User Function VB.NET Example

Private Function ValidateUser(ByVal strUsername As String, ByVal strPassword As String) _
As Boolean


'Return true if the username and password is valid, false if it isn't
Return CBool(strUsername = "admin" AndAlso strPassword = "password")
End Function

Listing 15: Validate User Method C# Example

private Boolean ValidateUser(String strUsername, String strPassword)
{
//Return true if the username and password is valid, false if it isn't
return ((strUsername == "admin") && (strPassword == "password"));
}

Listing 16: Assign Roles Function VB.NET Example

Private Function AssignRoles(ByVal strUsername As String) As String
'Return a | separated list of roles this user is a member of
If txtUsername.Text = "admin" Then
Return "author|editor"
Else
Return String.Empty
End If
End Function

Listing 17: Assign Roles Method C# Example

private String AssignRoles(String strUsername)
{
//Return a | separated list of roles this user is a member of
if (txtUsername.Text == "admin")
return "author|editor";
else
return String.Empty;
}

Create a logout.aspx web page.

Since users may perform a login it only seems logical to provide a means of logging out of the application. An effective way of accomplishing such a task is to put a hyperlink to the logout page:

Listing 18: Logout HyperLink

<asp:HyperLink id="hlLogout" runat="server" NavigateUrl="logout.aspx">Logout</asp:HyperLink>

The logout.aspx page can contain any information that you may want to display. The key actions here are to kill the session and sign the user out of the application. These actions are accomplished in the code-behind of logout.aspx

Listing 19: Logout Sub Routine VB.NET Example

Imports System.Web.Security


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load


Session.Abandon()
FormsAuthentication.SignOut()
End Sub

Listing 20: Logout Method C# Example

using System.Web.Security;


private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
Session.Abandon();
FormsAuthentication.SignOut();
}

Summary

[ Download Code ]

As you can see, the Web configuration file can become a powerful tool if you take the time to look into the options it provides. I have discussed both the authentication and the authorization elements, and provided a sample of how to use these elements to establish a login page for your application. As I earlier indicated, I wanted to include a variety of resources that may assist you further. Remember, programming should always be fun!

ASP.NET's Built-In Web Security

Applied Login Security

Simple Forms Authentication

Forms Authentication Against An XML File

Using Forms Authentication in ASP.NET - Part 1

ASP.NET forms authentication with roles

Forms Authentication Provider

ASP.NET Authentication

Feel free to discuss this article at my Blog.



User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-18 1:10:02 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search