
C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#
.pdfChapter 19: ASP.NET Security
Overview
The reasons to secure a Web site are well known and thus do not require a detailed discussion. A few of the reasons for securing a Web site include transfer of sensitive data over the Internet, exchange of sensitive data between Web applications, and risks of hack attacks.
Security is a critical issue for both Web application developers and administrators alike. It is undoubtedly one of the most confusing areas, and hence requires careful planning and designing. Web site developers and administrators must have a clear understanding of the various options, such as authentication, for securing their sites.
This chapter explores the different types of security implementations that can be used to secure an ASP.NET Web site. You'll also learn how the Microsoft .NET Framework assists in securing Web sites.
Introduction to ASP.NET Security
Security, in the context of an ASP.NET application, involves three fundamental operations. These operations are carried out during the lifetime of each secure ASP.NET Web application and are described as follows:
§Authentication: This is the process of validating the identity of a user, to allow or deny a request. Typically, authentication is a process of accepting the username and password from a user, and validating the username/password combination in a security database. In addition to this typical case, the authentication process can be more sophisticated. After the identity is verified and validated, the user is considered to be legitimate, and the resource request is fulfilled. Future requests from the same user, ideally, are not subject to the authentication process, until the user logs out of the Web application.
§Authorization: This is the process of ensuring that users with valid identity are allowed to access only those resources for which they have been assigned access rights. In other words, authorization is a check that is performed at every stage of the request-processing cycle on the Web server. This check ensures that access is given only to the allowed resources.
§Impersonation: This process enables an application to assume the identity of the caller, and in turn make requests to the other resources. Access to resources will be granted or denied based on the identity that is being impersonated. If the identity being impersonated has permissions to a resource, the application that impersonates the identity will also have the access permission to that resource.
Before delving deeper into the security system that is available with ASP.NET, let us review the security system that is made available to the Web sites by the underlying Web server. For the ASP.NET applications, the underlying Web server is Microsoft Internet Information Services (IIS). Therefore, every ASP.NET Web application can continue to leverage the security options provided by the IIS server. Let us now look at the security provided by the IIS server.
IIS security
Securing a Web application involves different aspects. The best place to start securing a Web application is by looking at the security methods provided by the Web server that
hosts the Web application. The IIS server has built-in support for authentication and authorization of user requests.
Authentication
The IIS server has built-in support for authenticating clients who request the Web content stored in an IIS Web site. Three different types of authentication can be implemented by using the IIS server:
§Anonymous Authentication: Allows all users to browse the Web site without prompting for a username and password. The access to the Web site resources is impersonated by the IIS server by using the IUSR_machinename account.
§Basic Authentication: Requires the users to enter a username/password combination for accessing the Web site. The major downside to this method of authentication is that the password is sent over the network in an unencrypted form, making it possible for unauthorized users to snoop the network packets and retrieve the password information easily.
§Integrated Windows Authentication: Requires the users to be valid Windows users in addition to fulfilling the basic authentication. In this mode, IIS will verify the username and password with a Windows Domain Controller. The access to the Web site is allowed only if the domain controller validates the username and password.
§Digest Authentication: Is similar to the basic authentication. However, this authentication uses a different way of transmitting the authentication credentials. This authentication sends a hash value over the network rather than the password. The hash value cannot be decrypted and hence the original text cannot be deciphered.
Authorization
The IIS server can be configured to control the resources that can be accessed by users. You can control the access permissions on an IIS Web site by marking the allowed operations on the Web site. The different permission levels include the following:
§Read: Allows users to retrieve and read the content stored in the virtual directory. This permission is assigned to most virtual directories.
§Write: Allows users to retrieve and modify the content stored in the virtual directory. If a Web site is open to receiving content over the HTTP protocol, the virtual directory used to store the received files must have the write permission. A typical example of this would be a virtual directory that stores the files that are uploaded as attachments to e-mail messages.
§Script source access: Allows users to view the source code of any server-side program.
§Directory browsing: Allows users to view the contents of the entire virtual directory. This is similar to viewing an FTP folder.
§Log visits: Keeps track of the number of users who visit the site, and records information about various details, such as the IP address of the client and the resources that are requested for.
§Index: Uses Microsoft Index Server to index the virtual directory. The contents of the directory can be retrieved in a search result using the Index Server.
In addition to the IIS permission levels, NTFS permissions can also be used to secure the files and directories on a Web server. The following are the different access permissions that can be assigned to users and groups for the files and directories on the server:
§Full Control: Allows users to have complete control on files and/or directories.
§Modify: Allows users to modify the contents of files and/or directories. However, users will not be able to delete files and/or directories.
§Read & Execute: Allows users to read the contents of the existing files and/or directories and execute any application stored in that folder. However, users will not be able to modify the contents of the files and/or directories.
§List Folder Contents: Allows users to view the contents of the folder. However, users will neither be able to read the contents of any file in the folder nor modify any contents.
§Write: Allows users to make changes to files and/or directories.
§No Access: Does not allow any access to files and/or directories.
Authentication in Web applications
Various ways exist to authenticate user access to Web applications. In intranet applications, it is possible to use Integrated Windows Authentication to authenticate user access and implement access control. But, in most of the Internet applications, it is not possible to use Windows authentication as it puts various restrictions. The following are two of these restrictions:
§Number of user accounts: Although Windows Active Directory can scale up to a large number of user accounts, managing all the user accounts for Internet applications (that involve millions of user accounts) can be a big management challenge, if not a nightmare. Therefore, most Web administrators and developers prefer an authentication mechanism that is based on databases, such as SQL databases.
§Licensing issues: If millions of users were to be authenticated against an Active Directory database, the Web site would need to procure user licenses for all the users. Thus, to say the least, it can prove to be an expensive proposition.
In classic ASP, authentication issues were addressed by security implementations that relied on cookies or client IP. This approach, typically, meant writing a lot of code and proved to be an unnecessary overhead for developers. The approach is very different from implementing security in Windows applications. In Windows, applications are developed in a way that maximizes the leverage on the services provided by the operating system. With ASP.NET, however, the days of writing tedious user validation code are gone. Developers can rely on the underlying Microsoft .NET Framework to provide security. They just need to focus on solving business problems and implementing the functionality in the Web site. Let us now explore the various authentication models that are supported by ASP.NET.
ASP.NET authentication options
The security section of the Web.config file contains the information related to the level and type of authentication services that would be provided for a Web application. Th e Web.config file is an XML file and is located in the root directory of a Web application. Various configuration options for an ASP.NET Web application can be controlled and configured from this XML file.
CrossReference
The system.web section of the Web.config file is used to control the various aspects of security that are provided to the Web application. An ASP.NET Web application can be provided with one of the following types of security:
§Windows: The application is secured by using Integrated Windows Authentication. In this method, access to a Web application is allowed only to those users who are able to verify their Windows credentials. Credentials can be verified against the Windows authentication database (SAM) or against Active Directory.
§Passport: The application is secured by using Microsoft Passport authentication. Passport is a single-sign-on technology developed by Microsoft for use on the Web. For more information on using Microsoft Passport, visit http://www.passport.com/business/.
§Forms: The application is secured by using a custom authentication model with cookie support.
§None: The application is not secured; access to the application does
not require authentication.
The system.web section has an <authentication> element that is used to specify the security settings. The following is the syntax of the <authentication> element:
<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>
</forms>
<passport redirectUrl="internal"/>
</authentication>
The various attributes of the <authentication> element are described as follows:
§Mode: Indicates the authentication mode to be used for the ASP.NET Web application.
§Forms: Indicates the Forms-based authentication that is used. The different suboptions that are used include the following:
o Name: Specifies the name of the cookie that will be
issued when a user is authenticated. This is the cookie that the ASP.NET application will check before processing requests from the client. If this cookie is found and is determined to be valid, ASP.NET will process the client request.
o LoginURL: Specifies the URL of the Web page to which a client will be redirected if the client is not authenticated.
o Protection: Specifies the level of protection that is applied to the cookie. The default value is All, which causes the cookie to be encrypted by using the 3DES algorithm. It also validates the cookie contents to ensure that the cookie is not tampered with. The other options include None, Encryption, and Validation. The None option specifies that the cookie is not encrypted or validated. This is as good as a nonsecure cookie access. Therefore, use this value only if the Web site has very low security requirements. The Encryption option specifies that the cookie contents are encrypted by using the 3DES algorithm, but contents of the cookie are not validated. Therefore, the contents of the cookie can be altered by someone during transmission. The Validation option specifies that the cookie is not encrypted. However, the cookie contents are validated to ensure that the cookie cannot be altered during data transmission.
o Timeout: Indicates the time after which the cookie will expire. If the site is visited before the timeout, the timeout value is refreshed. This is called sliding expiration. For example, if the timeout is 30 minutes and the user requests another document from the Web site after 10 minutes of inactivity, the timeout will occur if the user remains inactive for another 30 minutes.
o Path: Sets a path for the cookie. The path allows a Web page to share cookie information with other pages within the same domain. If the path is set to /mywebapp, all pages in /mywebapp and all pages in subfolders of /mywebapp can access the cookie.
§Credentials: Allows the application to specify the username and password combinations that are valid.
oPasswordFormat: Specifies the encryption format that is used for storing passwords. The available options include Clear, MD5, and SHA1. The Clear option indicates that no encryption is used. The MD5 option indicates that the MD5 algorithm is used. The SHA1 option indicates that the SHA1 algorithm is used.
§User: Defines the username and password combinations that
are valid.
o Name: Defines the username.
oPassword: Defines the password of the user.
§Passport: Specifies the configuration information if the authentication mode is set to Passport.
oRedirectURL: Specifies the URL to which the client will be redirected when a page requires Passport authentication, but the user has not logged on with a Passport.
Forms-based Authentication
ASP.NET includes a built-in feature, called forms-based authentication, which can be used to implement customized logic for authenticating users and authentication handlers without having to worry about session management using cookies. In forms-based authentication, when a user is determined to be unauthenticated, the user is automatically redirected to the login page. Some of the benefits of the forms-based authentication are the following:
§Developers can configure forms-based authentication for various parts of the Web site differently, because the Web.config file is a hierarchical XML document.
§Administrators and developers can change the authentication scheme quickly
and easily in the Web.config file.
§Administration is centralized because all the authentication entries are in one place — the Web.config file.
You can enable forms-based authentication for a Web application by setting the Authentication mode property to "Forms" in the Web.config file. The following is a sample code in the Web.config file used to enable forms-based authentication:
<configuration>
<system.web>
<authentication mode="Forms">
<!-- Assign a cookie named B2CBuySiteAuthCookie
when user is authenticated. The page used for validating user
credentials is userauth.aspx. Make sure the cookie is encrypted
and validated by setting the protection to All, the cookie will
timeout after 10 minutes -->
<forms name=".B2CBuySiteAuthCookie" loginUrl=
"userauth.aspx" protection="All" timeout="10" />
</authentication>
<authorization>
<!-- anonymous users will be denied access. This is needed to force forms-authentication -->
<deny users="?"/>
</authorization>
</system.web>
</configuration>
In this code:
§The authentication mode is forms-based authentication.
§The Userauth.aspx file is the Web page that is used for authenticating user credentials.
§The cookie protection level is set to All. This value causes the ASP.NET
runtime to not only encrypt the cookie contents, but also validate the cookie contents to ensure that the contents have not been modified on the network.
You can also add authorization support to sections of an ASP.NET Web application. To do so, you need to add the <location> element in the Web.config file. Consider the following sample code that uses the <location> element:
<!-- Require Authentication for Shopping Cart -->
<location path="Default.aspx">
<system.web>
<authorization>
<deny users="?" />
<allow users="Jack,Joe"/>
</authorization>
</system.web>
</location>
In this code, when an unauthenticated user attempts to access the Default.aspx page, ASP.NET will automatically redirect the request to the userauth.aspx page. After the user provides the valid credentials, the user is redirected to the Cart.aspx page.
The usernames specified can be certain specific usernames. In addition, you can use some special characters to represent usernames:
§*: Refers to all users
§?: Refers to all unauthenticated, anonymous users
In the previous sample code, only Jack and Joe will be allowed to access the Default.aspx page, and no unauthenticated, anonymous user will be allowed to access the Default.aspx page.
After you add the necessary code in the Web.config file for the forms-based authentication, you need to set the security configuration of the IIS virtual directory to "Allow Anonymous Access".
Let us now implement the forms-based authentication for an ASP.NET Web application. Complete the following steps:
1.Set the Authentication mode to "Forms" in the Web.config file. This file should be present in the same directory as the ASP.NET Web application.
2.<configuration>
3.<system.web>
4.
5.<authentication mode="Forms">
6.<!-- Assign a cookie named B2CBuySiteAuthCookie
7.when user is authenticated. The page used for validating
8.user credentials is userauth.aspx. Make sure the cookie
9.is encrypted and validated by setting the protection to
10.All, the cookie will timeout after 10 minutes -->
11.
12.<forms name=".B2CBuySiteAuthCookie" loginUrl=
13."userauth.aspx" protection="All" timeout="10" />
15. </authentication>
16.
17.<authorization>
18.<!-- anonymous users will be denied access.
19.This is needed to force forms-authentication -->
21. <deny users="?"/>
22.
23. </authorization>
24.
25.</system.web>
</configuration>
26.The next step is to create the login page that will accept and validate user credentials before assigning the client a session cookie. The login page will then redirect the user back to the page requested by the client. Write the following code in "Userauth.aspx" file:
27.<%@ Import Namespace="System.Web.Security " %>
28.<html>
29.<script language="VB" runat=server>
30.' Verify credentials
31.Sub Login_Click(Src As Object, E As EventArgs)
32.' Do complex hashing and look up other data sources to
33.' determine validity ;)
34.
35.If UserName.Value = "john" And UserPass.Value = "secret"
36.
37.'Credentials are ok, redirect back to the page that forced
38.'authentication, pass the user name and don't persist the cookie
39.FormsAuthentication.RedirectFromLoginPage(UserName.Value,F
alse)
40.
41. Else
42.
43. Msg.Text = "Invalid user name or password: Please try again"
44.
45.End If
46.End Sub
47.</script>
49.<body>
50.<form runat=server>
51.<h3><font face="Verdana">Please Sign-In</font></h3>
52.<table>
53.<tr>
54.<td>Login Name:</td>
55.<td><input id="UserName" type="text" runat=server/></td>
56.</tr>
57.<tr>
58.<td>Password:</td>
59.<td><input id="UserPass" type=password runat=server/></td>
60.</tr>
61.</table>
62.<asp:button text="Login" OnClick="Login_Click" runat=server/>
63.<asp:Label id="Msg" ForeColor="red" Font -Name="Verdana"
64.Font-Size="10" runat=server />
65.</form>
66.</body>
</html>
67.Finally, create the Default.aspx file with the following code:
68.<%@ Import Namespace="System.Web.Security " %>
70.<html>
71.<script language="VB" runat=server>
72.Sub Page_Load(Src As Object, E As EventArgs)
74.'Use the User object to retrieve information about the current
'user
75.Welcome.Text = "Hello, " + User.Identity.Name

76.
77. |
End Sub |
78.
79.Sub Signout_Click(Src As Object, E As EventArgs)
80.' logout from the web application and display login screen
82.FormsAuthentication.SignOut()
83.Response.Redirect("userauth.aspx")
85.End Sub
86.</script>
88.<body>
89.<h3><font face="Verdana">Using Forms Authentication</font></h3>
90.<form runat=server>
91.<h3><asp:label id="Welcome" runat=server/></h3>
92.<asp:button text="Signout" OnClick="Signout_Click" runat=server/>
93.</form>
94.</body>
</html>
Figure 19-1 and Figure 19-2 show the output of the preceding code. When a user requests the Default.aspx page, the ASP.NET run time checks for the presence of the specified cookie. If the cookie is not found, the user is prompted to sign on the form represented by the Userauth.aspx page. Once the user credentials are verified, ASP.NET makes the Default.aspx page accessible to the user by redirecting the browser to the Default.aspx page.
Figure 19-1: The Userauth.aspx page

Figure 19-2: The Default.aspx page
Integrating Security Methods
In certain cases, Web applications might need to be integrated with the security provided by Windows. One such case would be an intranet Web application that provides different levels of access to users depending on the Windows credentials. In this case, the Web applications can be secured by using Windows authentication.
Configuring Windows authentication for a Web application is quite simple. To do so, the Authentication mode must be set to "Windows" in the Web.config file. Consider the following sample code:
<configuration>
<system.web>
<authentication mode="Windows" />
</system.web>
</configuration>
In addition to this setting, you also need to set Integrated authentication in the virtual directory by using the IIS administration tool for Integrated Windows Authentication to work properly. To enable Integrated Windows Authentication for a Web application, complete the following steps:
1.Start the IIS administration tool and open the Properties dialog box for the Web application.
2.Select the Directory Security tab and click the Edit button to view or change the authentication methods. The Authentication Methods dialog box displays, as shown in Figure 19-3.
Figure 19-3: Setting Integrated Windows Authentication for a virtual directory in IIS
3.Check the Integrated Windows Authentication check box to enable Integrated Windows Authentication.