Securing ASP.NET Applications


In a Web application, there are normally resources that are restricted to certain users. For instance, in an online store application, there are usually two parts of the application. The first part, which allows people to select shopping items and purchase them, is available to anyone with Internet access. The second part, which consists of administration pages where store managers or store owners can manage the products, categories, orders and so on, is accessible to the manager or owner of that online store. In these cases, you need to protect those restricted resources so that they are only viewable by and accessible to the people who are supposed to see them. In other words, you need to secure your ASP.NET application.

Securing an ASP.NET application basically comes down to the following three techniques that can be applied separately or in conjunction with each other:

  • Authentication: The process of verifying that a user is really who he claims to be. Authentication is the most common type of security method. An application checks a user's credential by prompting him to supply the correct username and password.

  • Authorization: The technique to determine whether an authenticated user should be granted or denied access to a resource.

  • Impersonation: This process enables the application to operate on behalf of an authenticated user or an anonymous user who is currently accessing the application. This is to say that the application impersonates the user. Therefore, access to certain resources will depend on whether the user has access to those resources.

Securing a Web application using one or more of the aforementioned techniques is a serious business that requires careful planning. However, ASP.NET provides features that make it easy to accomplish these, either through configuration files or by coding.

Before you start devising a plan to secure your ASP.NET application, you should first understand the ASP.NET infrastructure in relation to its surrounding subsystems: the .NET Framework and IIS. Because ASP.NET is part of the .NET Framework, ASP.NET applications can utilize the low-level security features of the .NET Framework. Also, because all traffic from the user to the application and vice versa must go through IIS, understanding how you can use IIS to secure your application is also critical. Figure 6-9 depicts the relationship of the ASP.NET applications, the .NET Framework, and IIS.

click to expand
Figure 6-9: The ASP.NET infrastructure for security

One other important aspect to consider is that securing ASP.NET applications requires you to modify settings in the machine and application configuration files. Therefore, it is mandatory to understand how various configuration settings affect your applications, as discussed previously.

In this section you will find various methods for ASP.NET authentication, authorization, and impersonation. If the meanings of the three are not clear right now, do not worry. Each method comes with examples that should make them easier to comprehend.

Using Authentication

Put simply, authentication is the security technique that is commonly used. In authentication, a user must prove to the application that she is one of the users registered in the system's database or other data sources. A user must enter a username and password before she is granted access to a resource she requested. For authentication, ASP.NET works hand in hand with IIS using one of the following methods:

  • Windows authentication

  • Forms-based authentication

  • Microsoft Passport authentication

To enable authentication, you use the <authentication> element in the configuration file:

 <configuration>   <system.web>     <authentication mode="Windows|Forms|Passport|None">     </authentication>   </system.web. </configuration> 

where the mode attribute is assigned one of the authentication modes: Windows (the default), Forms, Passport, or None. Setting the mode attribute to None causes no authentication to be performed.

Note

The <authentication> element can only appear at the application configuration file on the root directory of the application, but not in the application configuration file on the subdirectories.

The following sections explain each of these authentication methods.

Windows Authentication

Windows authentication is called so because it relies on the Windows operating system user accounts. Windows authentication is something with which any ASP programmer should be familiar. In this section I briefly describe this type of authentication to refresh your memory.

In Windows authentication, IIS conducts the authentication process using one of the following three methods:

  • Basic authentication

  • Digest authentication

  • Integrated Windows authentication

The Basic authentication is the simplest of the three methods. This is widely used because it is an industry standard that works with most browsers. This is what happens when a user requests a resource from a restricted area on the server when the Basic authentication is enforced:

  1. IIS sends an HTTP "401 Unauthorized" header.

  2. The Web browser receives the message and displays a Login dialog box, prompting the user to enter her credentials.

  3. The Web browser passes the credentials to IIS.

  4. If the credentials are valid, IIS sends the requested page. Otherwise, it repeats step 1.

Note

In Basic authentication, the username and password sent to the server are not encrypted, making it possible for malicious hackers to steal them.

Digest authentication is similar to Basic authentication. However, the username and password are encrypted before being sent over the network. This authentication method only works in Internet Explorer browsers.

With Integrated Windows authentication, which is also known as NTLM or Kerberos, authentication happens automatically in the background. When you use Integrated Windows authentication, the browser sends the encrypted version of the user's Windows username and password to the server. Not surprisingly, this authentication method only works if the client is using a Windows operating system and an Internet Explorer browser.

Basically, no coding is necessary to apply Windows authentication. All you need to do is change the security setting for your ASP.NET application directory or any subdirectory below your application directory. Securing a directory forces the user to log in before they can access any resource in that directory or a directory below the directory you secure.

To secure a directory, do the following:

  1. From the Control Panel, select Administrative Tools and then double-click the Internet Service Manager icon.

  2. Select a directory to secure, right-click it, and select Properties.

  3. On the Properties dialog box for that directory, click the Directory Security tab.

  4. In the Anonymous Access and Authentication Control panel, click the Edit button. You should see the Authentication Methods dialog box like the one in Figure 6-10.

click to expand
Figure 6-10: Securing a directory using Windows authentication

The Authentication Methods dialog box shows the Windows security setting for the selected directory. There are two panels in that dialog box: the Anonymous Access panel and the Authenticated Access panel. The Anonymous Access check box in the first panel specifies whether anonymous access is allowed to the selected directory. If this check box is checked, the options selected in the Authenticated Access panel are ignored. The Authenticated Access panel allows you to select one of the three Windows authentication methods: Basic, Digest, or Integrated Windows authentication.

By default, as shown in Figure 6-10, the Anonymous Access check box is selected, indicating that no username and password is required for a user to access the resources in that directory. To apply authentication, uncheck the Anonymous Access check box and check one of the options in the Authenticated Access panel or a combination of the three options. Clicking the OK button on the Authentication Methods dialog box and then clicking OK on the Properties dialog box for that directory applies the authentication.

When a directory is secured, every time a user tries to access a resource in that directory, IIS tries to authenticate that user. For example, if Basic authentication is used, the user will be prompted to enter a username and password in the dialog box shown in Figure 6-11.

click to expand
Figure 6-11: Basic authentication

Once a username and a password are typed into the login window, the credentials will be matched to those in the Windows operating system. The user is only required to enter the correct username and password once. Subsequent requests carry an authentication token so that the user will not be asked to enter their credentials anymore. If the user enters incorrect credentials three times, a HTTP 401.2 header will be sent to the browser, notifying the user that they are not authorized to view the requested page.

Note

When using Windows authentication, you do not need to edit the configuration file.

Forms-Based Authentication

In this method of authentication, ASP.NET redirects HTTP requests that come without an authentication token to the specified login form. The user then must enter his credential (username and password) and submit the form. If the credential is authenticated by the application, the application adds an authentication cookie to the response and this cookie guarantees that the next request from the same user is not redirected to the login form again. On the other hand, the user will be denied access if he cannot supply the correct username and password.

In this method of authentication, IIS authentication is not used by the application. HTTP requests are passed to ASP.NET. Each request then follows the path depicted in Figure 6-12.

click to expand
Figure 6-12: Forms-based authentication

Even though IIS authentication is not used by the application, the method requires that the IIS Anonymous Access setting be enabled. Otherwise, all requests that do not meet the criteria for the enabled method of IIS authentication will be rejected and will never reach the ASP.NET application.

Using forms-based authentication requires you to set the <authentication> and <authorization> elements of the configuration file. The <authentication> element has the following format:

 <authentication mode="Windows|Forms|Passport|None">   <forms name="name" loginUrl="url"     protection="All|None|Encryption|Validation"     timeout="30" path="/">     <credentials passwordFormat="Clear|SHA1|MD5>       <user name="username" password="password" />     </credentials>   </form>   <passport redirectUrl="internal"/> </authentication> 

When using the forms-based authentication method, you will also be working with the System.Web.Security.FormsAuthentication class. The System.Web.Security namespace is implicitly imported, so you do not need to import it to use the FormsAuthentication class from your ASP.NET page.

The FormsAuthentication class has two properties:

  • FormsCookieName: The name of the cookie configured for the current application

  • FormsCookiePath: The path of the cookie configured for the current application

And, the following are some important methods of the FormsAuthentication class:

  • Authenticate: Authenticates the supplied user credentials against the configured credential store. This method accepts the username and password.

  • GetAuthCookie: Returns an authentication cookie for a given username. The return value type is System.Web.HttpCookie.

  • GetRedirectUrl: Returns the original URL requested by the user before the user is redirected to the login form.

  • RedirectFromLoginPage: Redirects the user to the original requested URL.

  • SignOut: Logs the user out.

Looking at a Form-Based Authentication Example

As an illustration of how you can use the forms-based authentication method, the following is an example. There are two files you need to create or modify. The first file, shown in Listing 6-29, is the application configuration file (web.config) that should be placed in the root directory of this application.

The second file is a file called Login.aspx file, shown in Listing 6-30, which is the Login form that each user must submit to send their credentials to the server.

Listing 6-29: The web.config File

start example
 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <system.web>     <authentication mode="Forms">       <forms name="formAuth" loginUrl="Login.aspx"/>     </authentication>     <authorization>       <deny users="?"/>     </authorization>   </system.web> </configuration> 
end example

The important point to note from the web.config file in Listing 6-29 is the <authorization> element, which basically says that anonymous users should be denied access:

 <authorization>   <deny users="?"/> </authorization> 

This will be explained further in the "Using Authorization" section.

The <authentication> element indicates that the authentication mode for this ASP.NET application is forms-based, and the login form for user login is the Login.aspx page:

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

Listing 6-30: The Login.aspx File

start example
 <html> <head> <title>Login Form</title> <script language="VB" runat="server"> Sub Login(sender As Object, e As EventArgs)   If userName.Text.Equals("mfranks") And _     password.Text.Equals("theLadyWantsToKnow") Then     FormsAuthentication.RedirectFromLoginPage( _       userName.Text, False)   Else     message.Text = "Login failed. Please try again."   End If End Sub </script> </head> <body> <form runat="server"> <asp:Label runat="server"    /> <hr> <h2>Login Form</h2> <table> <tr>   <td>Username:</td>   <td><asp:TextBox runat="server" /></td> </tr> <tr>   <td>Password:</td>   <td>     <asp:TextBox runat="server"       TextMode="password"      />   </td> </tr> <tr>   <td align="right" colspan="2">     <asp:Button runat="server"       Text="Login"       OnClick="Login"     />   </td> </tr> </table> </form> </body> </html> 
end example

The Login.aspx file is a normal Web form with a username TextBox control, a password TextBox control, and a Button control. This button is connected to the Login event handler.

The Login event handler checks the value entered into the userName and the password TextBox controls. If the userName and password are equal to the specified username and password, the FormsAuthentication class's RedirectFromLoginpage method is called, passing the username and False. In effect, this redirects the user to the original page he requested and sets the authentication cookie to the response:

 FormsAuthentication.RedirectFromLoginPage( _ userName.Text, False) 

The Login form in Listing 6-30 looks similar to Figure 6-13. Note that the original URL is added as the value of the ReturnUrl parameter in the query string.

click to expand
Figure 6-13: The Login form

Putting the Credentials in the Configuration File

The previous example showed how you can use forms-based authentication methods for one user whose username and password is hard-coded in the Login event handler. Although this is an easy-to-write page, sometimes it is not practical to hard-code the user's credentials. Also, sometimes you want more than one user to be able to log in to the application.

ASP.NET allows you to specify multiple users that should have access to your application in the application configuration file. Using this method, you do not need to hard-code the user credentials in your code.

The following example is the modification of the previous example. Listing 6-31 shows the web.config file, and Listing 6-32 shows the login page.

Listing 6-31: The web.config File

start example
 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <system.web>     <authentication mode="Forms">       <forms name="formAuth" loginUrl="Login.aspx" >         <credentials passwordFormat="Clear">           <user name="mfranks" password="theLadyWantsToKnow"/>           <user name="ken" password="vancouver"/>         </credentials>       </forms>     </authentication>     <authorization>       <deny users="?"/>     </authorization>   </system.web> </configuration> 
end example

The difference between the web.config file in Listing 6-29 and the one in Listing 6-31 is that in the latter the <forms> element contains the <credentials> element. The <credentials> element is where you put all users' credentials. Theoretically, you can write as many <user> elements as you want. In the application configuration file in Listing 6-31, there are two users:

 <credentials passwordFormat="Clear">   <user name="mfranks" password="theLadyWantsToKnow"/>   <user name="ken" password="vancouver"/> </credentials> 
Note

Assigning "Clear" to the passwordFormat attribute of the <credentials> element causes the credentials to be sent to the server without using any encryption. Other possible values for this attribute are MD5 or SHA1, which make the credentials encrypted using the MD5 and SHA1 encryption algorithms (respectively) before the credentials are sent to the server.

Listing 6-32: The Login.aspx File

start example
 <html> <head> <title>Login Form</title> <script language="VB" runat="server"> Sub Login(sender As Object, e As EventArgs)   If FormsAuthentication.Authenticate( _     userName.Text, password.Text) Then     FormsAuthentication.RedirectFromLoginPage( _       userName.Text, False)   Else     message.Text = "Login failed. Please try again."   End If End Sub </script> </head> <body> <form runat="server"> <asp:Label runat="server"    /> <hr> <h2>Login Form</h2> <table> <tr>   <td>Username:</td>   <td><asp:TextBox runat="server" /></td> </tr> <tr>   <td>Password:</td>   <td>     <asp:TextBox runat="server"     TextMode="password"      />   </td> </tr> <tr>   <td align="right" colspan="2">     <asp:Button runat="server"       Text="Login"       OnClick="Login"     />   </td> </tr> </table> </form> </body> </html> 
end example

The login page in Listing 6-32 is different from the one in Listing 6-30 in that the username and password are not hard-coded. Instead, you call the Authenticate method of the FormsAuthentication class to authenticate the username and password supplied by the user:

 If FormsAuthentication.Authenticate( _   userName.Text, password.Text) Then 

Passport Authentication

Passport authentication is Microsoft's initiative that offers a centralized authentication service that is basically a forms-based authentication service (see http://www.passport.com). To provide Passport authentication in a Web site, the owner must download, install, and configure the Passport SDK from http://www.passport.com/business. This does not come free, though. You must pay a fee to obtain the SDK.

To use Passport authentication in your ASP.NET application, you must specify "Passport" as the value for the mode attribute of the <authentication> element:

 <authentication mode="Passport"> </authentication> 

The following illustrates how Passport authentication works:

  1. A client requests a protected resource from your Web site.

  2. For the first request, the request does not contain a valid Passport ticket, so your Web server redirects the client to the Passport Logon service. The redirection URL contains the original requested resource, just like the one in forms-based authentication.

  3. The user logs in to the Login form presented by the Passport logon server. The username and password are submitted using Secure Sockets Layer (SSL).

  4. The logon server authenticates the user and, if the authentication is successful, redirects the user to the original URL in your Web site with the authentication ticket encrypted in the query string.

  5. Your Web server detects the presence of the authentication ticket this time and grants access to the requested resource.

From the user's point of view, it can be beneficial because each user only has one username and password to access multiple Web sites.

Using Authorization

Authorization means checking if an authenticated user has access to a resource. Imagine an office where each employee has a card to go into the office building as well as to enter each room in the office. To enter the building, an employee must swipe their card into a machine. The machine authenticates them. However, once in the building, not all employees have access to all rooms. For example, a deliveryman may not have access to the boardroom. When he swipes his card to enter the room, he will be rejected access to it. The director, on the other hand, has access to the boardroom, and she can use her card to open the boardroom door. It is said that the director is authorized to enter the boardroom but not the deliveryman.

Similarly, authenticated users may have different access to different resources in a Web application. ASP.NET allows you to determine who can access which resource by editing the configuration file for an application.

There are two types of authorization in ASP.NET:

  • File authorization: This type of authorization relies on the Windows operating system's Access Control List (ACL) to decide whether a user should have access to a resource. To view the ACL of a file or directory, right-click a file or directory in Windows Explorer, select Properties, and click the Security tab. You should see a dialog box like the one in Figure 6-14. File authorization is active when you use Windows authentication (see the section "Using Impersonation").

    click to expand
    Figure 6-14: A file's/directory's ACL

  • URL authorization: This type of authorization maps user identities to the directories specified in the requested URLs. To establish the URL authorization for a directory, you create an application configuration file that contains an <authorization> element in that directory. Thanks to the inheritance nature of a configuration file as explained in the previous section, the <authorization> element specified in a directory applies to all its subdirectories. However, you can apply different URL authorizations by placing a different application configuration file in a subdirectory.

You configure URL authorization in ASP.NET using the <authorization> setting under the <system.web> element. The syntax for the <authorization> setting is as follows:

 <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> 

The <authorization> element can have two subelements, <allow> and <deny>, both of which are optional. The <allow> element specifies the users/roles allowed access to a resource. The <deny> element specifies the users/roles that must be revoked access to a resource.

Both <allow> and <deny> elements can contain three optional attributes: users, roles, and verbs.

Note

For more information on role-based security, see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguidnt/html/cpconcodeaccesssecurity.asp.

In addition to names, the users attribute can accept two special identities:

  • ?: Represents the anonymous identity

  • *: Represents all identities

The section "Using Authentication" demonstrated how to use the ? character. For instance, the following <authorization> element instructs ASP.NET to reject the anonymous user access to all resources in the directory where the application configuration that contains the <authorization> element resides:

 <authorization>   <deny users="?"/> </authorization> 

The following <authorization> element allows ken and denies rob:

 <authorization>   <allow users="ken"/>   <deny users="rob"/> </authorization> 

The following code snippet denies all users except ken:

 <authorization>   <allow users="ken"/>   <deny users="*"/> </authorization> 

You can add the verbs attribute to the <allow> and <deny> elements to specify the HTTP methods (such as POST, GET, HEAD) that apply to that element. For instance, the following <authorization> element allows all users to request a resource using the GET method, but not the POST method.

 <authorization>   <allow verb="GET" users="*"/>   <deny verb="POST" users="*"/> </authorization> 

The following code snippet allows all users to request a resource using the GET method, but only ken can use the POST method:

 <authorization>   <allow verb="GET" users="*"/>   <allow verb="POST" users="ken"/>   <deny verb="POST" users="*"/> </authorization> 

Using Impersonation

Impersonation enables the application to operate on behalf of an authenticated user or an anonymous user who is currently accessing the application. Therefore, access to certain resources depends on whether the user has access to those resources. By default, impersonation is disabled for backward compatibility with classic ASP and is used only to avoid dealing with authentication and authorization issues in the ASP.NET application code.

With impersonation, you rely on IIS to authenticate the user and continue with one of the following:

  • If authentication was successful, IIS passes an authenticated token to the ASP.NET application. The ASP.NET application then impersonates this user.

  • If authentication failed, IIS passes an unauthenticated token to the ASP.NET application. The ASP.NET application will then impersonate the anonymous user, which is IUSR_MachineName.

The ASP.NET application then impersonates the user and relies on the settings in the Windows operating system ACL to either allow or revoke the user access to the requested resource.

Impersonation can be a convenient way of securing your ASP.NET applications if you already have an extensive list of Windows accounts.

To use impersonation, you use the <identity> element under the <system.web> element in the configuration file of the ASP.NET application you would like to secure. The syntax for this element is as follows:

 <identity   impersonate="true|false"   userName="username"   password="password"/> 

To enable impersonation, set the impersonate attribute to true. The userName and password attributes are optional.

As an example, the following application configuration file will impersonate the user Administrator:

 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <system.web>     <identity       impersonate="true"       userName="Administrator"       password="popsicleToes"     />   </system.web> </configuration> 




Real World. NET Applications
Real-World .NET Applications
ISBN: 1590590821
EAN: 2147483647
Year: 2005
Pages: 82

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net