ASP.NET Security: An Introductory Guide to Buil...

We were unable to locate this content in de-de.

Here is the same content in en-us.

ASP.NET Security: An Introductory Guide to Building and Deploying More Secure Sites with ASP.NET and IIS
MSDN Magazine

ASP.NET Security

An Introductory Guide to Building and Deploying More Secure Sites with ASP.NET and IIS

Jeff Prosise
This article assumes you're familiar with the .NET Framework
Level of Difficulty     1   2   3 
SUMMARY ASP.NET and Microsoft Internet Information Services (IIS) work together to make building secure Web sites a breeze. But to do it right, you have to know how the two interrelate and what options they provide for securing access to a Web site's resources. This article, the first in a two-part series, explains the ABCs of Web security as seen through the eyes of ASP.NET and includes a hands-on tutorial demonstrating Windows authentication and ACL authorizations. A range of security measures and authentication methods are discussed, including basic authentication, digest authentication, and role-based security.
There's an old adage among developers that says building security into software is like paying taxes. You know it's important and you know you must do it sooner or later, but you put it off as long as you can and when you finally do it, you do so only because you have to. You might not go to jail for building insecure applications, but security is no less important because of it. In many applications—Web applications in particular—security isn't a luxury; it's a necessity.
      Security is a big deal in network applications because by nature those applications are available to (and vulnerable to misuse by and attacks from) a larger population of users. When the network to which an application is deployed is the Internet, security becomes even more important because the list of potential users grows to about four billion. Web security is a broad and complicated subject. Much of the ongoing research in the field has to do with hardening Web servers against attacks. Microsoft® Internet Information Services (IIS) administrators are all too aware of the past security holes in IIS and of several patches and security updates from Redmond. But this article isn't about protecting servers from buffer overruns and other hack attacks; rather, this article is about using ASP.NET to build secure sites that serve up pages only to authorized users.
      Most sites built with ASP.NET fall into one of three categories:
  • Sites whose content is freely available to everyone.
  • Internet sites that serve the general population but require a login before displaying certain pages. eBay is a great example of such a site. Anyone can browse eBay and view the ongoing auctions, but when you place a bid, eBay requires a user name and password. eBay also has a feature named "My eBay" that lets you review the auctions you've bid on. Because My eBay pages are personalized for individual users and because they contain private information such as maximum bid prices, you must log in before viewing them.
  • Intranet sites that expose content to a controlled population of users—for example, a company's employees—who have accounts in a Windows® domain (or set of domains). Sometimes these sites support a limited degree of Internet access, too, so authorized users can access them from anywhere an Internet connection is available.
      Sites that fall into the first category require no special protection beyond what the Web server provides. Sites in the second and third categories require some form of application-level security to identify authorized users and prevent illicit accesses. ASP.NET provides that application-level security. It works in conjunction with IIS and the Windows security subsystem to provide a solid foundation for building secure sites. And it builds on what IIS has to offer to make deploying secure sites as easy as possible.
      This is the first in a two-part series on building secure Web sites with ASP.NET. In this installment, you'll learn how ASP.NET integrates with IIS and Windows and how the three can be combined to protect resources using Windows authentication and access control list (ACL) file authorizations. Part two of this article will cover ASP.NET forms authentication—a cool new feature of ASP.NET that lets you secure sites using a combination of form-based logins and URL resource authorizations.

Understanding Web Security

      At the application level, Web security is first and foremost about securing pages so that they can't be retrieved by unauthorized users—for example, preventing non-managers from viewing pages containing salary data and performance evaluations on the company intranet or preventing other people from viewing your My eBay pages. At a slightly deeper level, you might want to know who requested the page so you can personalize it for that individual. Either form of protection requires two overt actions on the part of the application: identify the originator of each request and define rules that govern who can access which pages
      A Web server identifies callers using a mechanism called authentication. Once a caller is identified, authorization determines which pages that particular caller is allowed to view. ASP.NET supports a variety of authentication and authorization models. Understanding the options that are available to you and how they interrelate is an important first step in designing a site that restricts access to some or all of its resources or that personalizes content for individual users.


      Authentication enables the recipient of a request to ascertain the caller's identity. The caller might claim to be Bob, but you don't know he really is Bob unless you authenticate him. ASP.NET supports three types of authentication: Windows authentication, Passport authentication, and forms authentication.
      When Windows authentication is selected, ASP.NET looks to IIS for help. IIS does the hard part by authenticating the caller. Then it makes the caller's identity available to ASP.NET. Let's say Windows authentication is enabled and Bob requests an ASPX file. IIS authenticates Bob and forwards the request to ASP.NET along with an access token identifying Bob. ASP.NET uses the token to make sure Bob has permission to retrieve the page he requested. ASP.NET also makes the token available to the application that handles the request so that at its discretion, the application can impersonate Bob—that is, temporarily assume Bob's identity—to prevent code executed within the request from accessing resources that Bob lacks permission to access.
      For Web applications, Windows authentication is typically used in the following scenarios:
  • Your application is deployed on the company's intranet and everyone who uses it has an account that they can use to log in and access network resources.
  • Your application is primarily intended for use on the company intranet, but you'd also like it to be possible for employees to be able to log in and use the application remotely—that is, from outside the firewall.
      The overarching goal of Windows authentication is to map incoming requests to user accounts on your Web server (or in the Web server's domain). In addition to preventing users who lack the proper logon credentials from accessing parts of your Internet site that require authenticated access, Windows authentication lets you use the operating system's built-in security mechanisms in order to protect files and any other resources from unauthorized access by authenticated users.
      Passport authentication relies on Microsoft Passport to authenticate users. Passport is a Web service that front-ends a massive database of user names and passwords maintained by Microsoft. Users who register with Passport can be authenticated anywhere on the Internet by applications that present login credentials to Passport. If Passport determines that the credentials are valid, it returns an authentication ticket that the application can encode in a cookie to prevent the user from having to log in time and time again. If you would like to see further information about Passport, check out the Passport SDK, which you can download from the Microsoft Web site.

Figure 1 Forms Authentication
Figure 1 Forms Authentication

      Forms authentication relies on login forms in Web pages to authenticate users. Figure 1 shows an example of forms authentication in action on eBay. You can surf most of eBay's site without logging in. But to bid on an item or go to My eBay, you have to enter a user name and password to let eBay know who you are. Windows authentication isn't very practical in this scenario because eBay doesn't want to assign each of its millions of users a Windows account on its servers. Forms authentication fits the bill nicely because it doesn't require users to have Windows accounts. It's perfect for Internet sites designed to serve the general population but that also have to know who a user is before allowing access to certain pages. Forms authentication is as old as the Web, but ASP.NET makes it incredibly easy as you'll see later in this article.
      You tell ASP.NET what type of authentication, if any, to use through Web.config files. The following Web.config file enables forms authentication for the corresponding application:
    <authentication mode="Forms" />
      Other valid mode values include None, Windows, and Passport. The default, defined in Machine.config, is Windows. The authentication mode is an application-wide setting that can only be set in the application root and can't be overridden in subordinate Web.config files. You can't use Windows authentication in one part of an application and forms authentication in another.


      Authentication is an important element of Web security—indeed, of network security in general—because it establishes trust. You can't trust a user if you don't know who he or she is.
      Authorization is the other half of the security equation. Once you know who a user is, authorization determines what resources that person can access. On a company intranet, for example, you might want to prevent rank-and-file employees from accessing files and directories containing payroll data. That's what authorization is for. ASP.NET supports two forms of authorization: ACL authorization (also known as file authorization) and URL authorization.
      ACL authorization is based on file system permissions. Most Web servers that run IIS and ASP.NET use the NTFS file system. NTFS uses ACLs to protect file system resources—that is, files and directories. It's trivial, for example, to tag a file with an ACL that permits only system administrators to read it. You simply pop up the file's property sheet, go to the Security page, remove the security principals (users and groups) that are currently listed, and add administrators. If you don't want Bob to view a particular ASPX file, you can deny Bob read access to the file in an ACL and Bob will be greeted with an access denied error when he tries to view the page. Because ACL checks are performed against access tokens representing Windows security principals, ACL authorization is typically used in scenarios where Windows authentication is used, too.
      URL authorization works differently. Rather than rely on NTFS permissions to protect resources, it relies on configuration directives in Web.config files. URL authorization is wholly a function of ASP.NET and does not require the complicity of IIS. It's most often used with forms authentication, but can be used with other authentication types as well.

IIS Security

      Since IIS is a Web server, its primary job is to accept connections from remote clients and respond to HTTP requests arriving through those connections. Most of the requests are HTTP GET and POST commands requesting HTML files, JPEG files, ASPX files, and other file system resources. Obviously, you don't want someone who connects to your Web server to be able to retrieve just any file. IIS protects a server's content in four ways:
  • Web applications are deployed in virtual directories that are URL-addressable on the server. Remote clients can't arbitrarily grab files outside virtual directories and their subdirectories.
  • IIS assigns every request an access token that enables the operating system to perform ACL checks on the resources used in the request. If the request runs as Bob and Bob isn't allowed to read Hello.html, then the request will fail when it attempts to read Hello.html. In addition, IIS makes Bob's access token available to ASP.NET so that ASP.NET can perform access checks of its own.
  • IIS supports IP address and domain name restrictions, enabling requests to be granted and denied based on the IP address or domain of the requesting entity.
  • IIS supports encrypted HTTP connections using the Secure Sockets Layer (SSL) family of protocols. SSL doesn't protect resources on the server per se, but it does prevent eavesdropping on conversations between Web servers and remote clients.
      All of these protection mechanisms are important to ASP.NET programmers, but the second item listed merits special consideration because ACL checks are wholly dependent upon the identity assigned to a request, and when Windows authentication is the chosen form of authentication, ASP.NET works closely with IIS to resolve issues involving identity.
      IIS runs in a process named Inetinfo.exe. Inetinfo.exe typically runs using the identity of the built-in SYSTEM account, which is highly privileged on the host machine. Requests forwarded to ASP.NET by IIS don't run as SYSTEM, however. They're assigned the identity of a specific user. Which user depends on the configuration of the requested resource.
      Through the IIS configuration manager found under Administrative Tools, IIS permits authentication control to be applied to individual files and directories. A given file or directory can be configured to allow anonymous access (access by unauthenticated users), authenticated access, or both. Let's say a request comes in for a file that supports anonymous access. By default, the request executes as IUSR_machinename, where machinename is the Web server's machine name. IUSR_machinename is a special account that's created when IIS is installed. You can use the IIS configuration manager to map anonymous requests to other accounts, but assuming you don't change the defaults, requests from anonymous users are tagged with IUSR_machinename's access token. It follows that Web pages intended for anonymous users should not be tagged with ACLs that deny access to IUSR_machinename.
      If, on the other hand, the requested file requires authenticated access, IIS assigns the request the identity of the account whose credentials the requestor supplies. If the user is Bob and can prove as much to IIS, then the request is tagged with Bob's access token.
      How does IIS ascertain a requestor's identity for authenticated accesses? How, for example, does it know that Bob is Bob? It depends on the type of authentication used. IIS supports four different forms of authentication: basic authentication, digest authentication, integrated Windows authentication, and SSL client certificates. As far as ASP.NET is concerned, all fall under the category of Windows authentication.
      Basic and digest authentication rely on user names and passwords to authenticate users. When the client is a browser, the browser prompts the user for a user name and password and transmits them to the Web server. Basic and digest authentication work well over the Internet because they piggyback on HTTP. Integrated Windows authentication uses Windows logon credentials to authenticate users. It's ill-suited to general Internet use, in part because both client and server must support Windows security protocols, and also because the client must validate against a domain controller that it can't get to through a firewall. SSL client certificates are also limited primarily to intranet use because they require clients to be outfitted with digital certificates.

ASP.NET Security

      Figure 2 shows the relationship between IIS and ASP.NET. When IIS receives a request for a file registered to ASP.NET (for example, an ASPX file), it hands the request off to an ISAPI DLL named Aspnet_isapi.dll. Aspnet_isapi.dll runs in the same process as IIS—that is, inside Inetinfo.exe. ASP.NET applications run in a separate process named Aspnet_wp.exe. Aspnet_isapi.dll forwards requests to Aspnet_wp.exe using a named pipe. When the request reaches the worker process, it is assigned to a specific application executing in a specific AppDomain. Once inside an AppDomain, the request travels through the ASP.NET HTTP pipeline, where it is examined by various HTTP modules and ultimately processed by the HTTP handler that corresponds to the resource type requested. Machine.config contains the master list that maps file types to HTTP handlers.

Figure 2 Relationship between IIS and ASP
Figure 2 Relationship between IIS and ASP

      The architecture in Figure 2 changes somewhat when ASP.NET is paired with IIS 6.0. Slated for release in 2002 with Windows Server 2003, IIS 6.0 will feature a more robust security model that gives IIS administrators the ability to segregate applications into surrogate processes very much like Aspnet_wp.exe. In IIS 6.0, there is no Aspnet_wp.exe; instead, IIS provides the worker process. At the time of this writing, Microsoft plans to connect Inetinfo.exe to worker processes using Local Procedures Calls (LPCs) rather than named pipes.
      What does all of this have to do with security? When Aspnet_isapi.dll forwards an HTTP request to Aspnet_wp.exe, it also forwards the access token that it obtained from IIS. That access token is typically one of the following: an IUSR_machinename token representing an unauthenticated user, or a token representing an authenticated security principal (for example, Bob).
      Before processing the request by sending it through the targeted application's HTTP pipeline, Aspnet_wp.exe does the following:
  • It performs an ACL check on the requested resource using the access token presented to it. If, for example, the request is a GET command asking for Foo.aspx, the access token represents Bob, and Foo.aspx has an ACL that denies read permission to Bob, then ASP.NET fails the request with an access denied error. ASP.NET performs this ACL check regardless of whether impersonation is enabled in ASP.NET.
  • It makes the access token available to the application that handles the request so that, if desired, the application can impersonate the caller and protect resources guarded by ACLs from code executed during the request.
      The importance of these actions cannot be overstated. The ACL check that ASP.NET performs before processing the request means you can deny Bob access to an ASPX file simply by tagging that file with an ACL that denies Bob read access. The fact that ASP.NET makes the caller's access token available for impersonation purposes means you, the developer, have some latitude in deciding what identity to use when processing the request. The right choice depends on what the application is designed to do and how it's designed to do it. I'll provide some background to enrich your understanding.
      By default, Aspnet_wp.exe runs as ASPNET, a special account that's set up when ASP.NET is installed. ASPNET is a member of the Users group, which means it's privileged enough to perform most of the actions a legitimate application might want to perform, but restricted enough to prevent certain kinds of attacks. Unless you specify otherwise, requests executed by ASP.NET use Aspnet_wp.exe's identity. Therefore, by default, requests run as ASPNET. Among other things, this means that barring configuration changes, there are certain actions an ASP.NET application can't perform, such as modifying entries in the HKEY_LOCAL_MACHINE section of the registry.
      The other option is to execute the request using the access token provided by IIS, a technique known as impersonation. Impersonation is enabled by including the following statement in the <system.web> section of a top-level Web.config file or modifying the <identity> element already present in Machine.config:
<identity impersonate="true" />
      If IIS assigns a request the identity of IUSR_machinename, impersonation won't buy you much because IUSR_machinename is a weak account that enjoys few privileges on the host machine. But if Windows authentication is enabled and IIS presents ASP.NET with a token representing the actual requestor, impersonation ensures that the application can't do anything on the Web server that the requestor isn't allowed to do.
      To further complicate matters, Aspnet_wp.exe can be configured to run as a principal other than ASPNET. Suppose you write an ASP.NET application that must have wider-ranging permissions than those afforded ASPNET—for example, the freedom to write to any part of the registry. You can configure Aspnet_wp.exe to run as SYSTEM by changing the statement
<processModel userName="machine" ... />
in Machine.config to read:
<processModel userName="SYSTEM" ... />
This enables your application to do almost anything it wants on the host machine, but it also makes ASP.NET less resistant to attacks. SYSTEM was the default when ASP.NET was in beta, but that was changed shortly before the product shipped.
      Another possible complication arises from the fact that in IIS 6.0, ASP.NET requests will default to Network Service rather than ASPNET. If you use ACLs to allow access to the ASPNET account while denying access to other security principals and find that requests mysteriously fail with access denied errors after you install IIS 6.0, modify your ACLs to allow access to Network Service rather than ASPNET.
      Clearly, the identities assigned to the ASP.NET worker process and to the requests that it executes play crucial roles in determining how successful an application is in carrying out its appointed mission. If your head is spinning right now trying to make sense of it all, don't fret; ASP.NET security will be far easier to grasp once you've experienced it firsthand. In the meantime, here are some guidelines to help you sort through the options and figure out which of them really matter for a given deployment scenario:
  • If your application requires no special protection—if all of its pages can be freely browsed by anyone and none are personalized for individual users—you needn't bother with application-level security. Just grant Everyone access to the application's files and be done with it.
  • If you're building an intranet application or any application whose permissions are based on mapping incoming requests to Windows accounts on your server, you'll probably use Windows authentication and ACL authorization. In that case, you'll use operating system ACLs to restrict access to pages that aren't intended for everyone. You may or may not enable impersonation, depending on the needs of the application.
  • If you're building an Internet application that serves the general public but want to secure access to certain pages, you'll most likely use forms authentication and URL authorization. In that case, you'll leave impersonation disabled and rely on credentials entered in login forms as the basis for authorizations. Many of the aformentioned issues regarding IIS and access tokens fall by the wayside in this scenario because you grant Everyone access to the application's files and rely on URL authorizations in Web.config to protect them.
      A final thought to keep in mind is that if you use ACLs to limit access to files and directories in an ASP.NET application, always grant the ASPNET account—or whatever account Aspnet_wp.exe runs as—read access to them. Otherwise, ASP.NET itself will be unable to read them and you'll experience all kinds of access denied errors that you probably didn't expect.

Windows Authentication

      Windows authentication is one of the options that ASP.NET gives you for identifying callers. Because Windows authentication maps incoming requests to accounts on the Web server or in the Web server's domain, you don't use it to generically expose content to all comers over the Internet. Instead, you use it to serve content to a well-defined populace—a populace that you control through Windows user accounts. Windows authentication on the front end is typically paired with ACL authorization on the back end to control access to the resources that your application exposes. But it works with URL authorization, too.
      Recall that Windows authentication comes in four forms: basic, digest, integrated, and client certificate. All map incoming requests to accounts on your network, but each does so in a different way. The next several sections describe the inner workings of basic, digest, and integrated Windows authentication and the user experiences that they convey. After that, I'll put Windows authentication to work in a real ASP.NET application.

Basic Authentication

      Basic authentication is an HTTP standard. It's documented in RFC 2617, which you can read online at Basic authentication transmits a user name and password in each request. IIS maps the user name and password to an account on the Web server, producing an access token that can be used to perform ACL-based security checks.
      It sounds simple, and it is. To demonstrate how basic authentication works, suppose your company deploys a series of Web pages containing information that only employees should be able to see. The IT staff places the files in a virtual directory on your Web server and configures IIS to disallow anonymous access to that directory and to require basic authentication. The first time you attempt to retrieve a page from that directory, the Web server returns a 401 status code indicating that authentication is required. It also includes in the response a WWW-Authenticate header identifying the type (or types) of authentication that it accepts. (The details differ slightly when a proxy server is involved, but the principle is valid nonetheless.) Here's a portion of a response returned by IIS 5.0 indicating that access to the requested resource requires basic authentication:
HTTP/1.1 401 Access Denied
Server: Microsoft IIS-5.0
WWW-Authenticate: Basic realm="jupiter"
      Your browser responds by popping up a dialog box asking for a user name and password (see Figure 3).

Figure 3 Basic Authentication
Figure 3 Basic Authentication

It then concatenates the user name and password to a string that identifies the authentication type, base-64-encodes the result, and transmits it to the browser in the Authorization header of an HTTP request. Here's the Authorization header transmitted by Internet Explorer 6.0 following a login with the user name "Jeff" and the password "imbatman":
Authorization: Basic SmVmZjppbWJhdG1hbg==
And here are the contents of the base-64-encoded portion of the header after decoding:
      To prevent you from having to log in again and again, the browser includes the same Authorization header in future requests to the same realm. A realm is simply a logical security space that encompasses all or part of a Web site.
      All authentication mechanisms have pros and cons. What's good about basic authentication is that it works with virtually all browsers, it provides an easily used and understood means to solicit user names and passwords, and it works well with firewalls. The downside of basic authentication is that it transmits user names and passwords in clear text. If used over an unencrypted channel, there's nothing to prevent requests from being intercepted and used to gain access to your server (or other servers where the caller's credentials are valid). In addition, some users consider pop-up user name and password dialogs intrusive.
      If you use basic authentication and the lines to your Web server aren't physically secured, be sure you use it over HTTPS, not HTTP. Otherwise, you'll secure access to honest (or technically unsophisticated) users, but leave yourself vulnerable to attacks by others.

Digest Authentication

      Digest authentication is similar to basic authentication. When you attempt to access a resource guarded by digest authentication, the browser solicits a user name and password by popping up a dialog box. The Web server uses the credentials that you enter to assign an identity to the request. The big difference between basic and digest authentication is that digest doesn't transmit clear-text passwords. Instead, it passes an authentication token that is cryptographically secure. As a result, you can use it over unencrypted channels without fear of compromising your Web server.
      The inner workings of digest authentication are also documented in RFC 2617. When the client first requests a resource guarded by digest authentication, the server returns a 401 error and includes a "nonce"—a string of 1s and 0s—in a WWW-Authenticate header. The browser responds by prompting for a user name and password. It then transmits the user name back to the server, along with a hash or "digest" computed from the combined user name, password, and nonce. The server authenticates the request by performing its own hash on the user name, password, and nonce. The password the server uses doesn't come from the client; it comes from the server itself (or from a connected server). If the hashes match, then the user is authenticated. Significantly, digest authentication never requires a plain-text password to be transmitted over an HTTP connection. It's also compatible with proxy servers.
      Digest authentication offers the following advantages. Like basic authentication, it provides an easily understood means for identifying callers, and it works with firewalls. In addition it's far more secure over ordinary HTTP than basic authentication.
      But there are three primary disadvantages. First, digest authentication requires a modern browser that supports digest authentication. For Microsoft Internet Explorer users, version 5.0 or higher is required. Second , it requires passwords to be stored in plain text (or in a reversible encrypted form that can be converted to plain text). This is contrary to the normal security model in Windows, which stores one-way password hashes in lieu of plain-text or encrypted passwords to protect the passwords if the server is compromised. Finally, like basic authentication, digest authentication uses pop-up dialog boxes to prompt for user names and passwords. Due to these restrictions, and because digest authentication doesn't support delegation (the ability to make a call from one machine to another and have the call execute as the caller on the remote machine) on Windows 2000 servers, digest authentication is not widely used.

Integrated Windows Authentication

      Integrated Windows authentication uses Windows logon credentials to authenticate users. Rather than prompt a user for a user name and password and transmit them over HTTP, a browser asked to identify the user through integrated Windows authentication carries on a conversation with the Web server and identifies the user using that person's login identity on the client. In other words, if Bob logs in to his Windows PC, starts Internet Explorer, and requests a resource protected by integrated Windows authentication, a handshake ensues between Internet Explorer and the Web server, and Bob's request executes as Bob on the server. Obviously, Bob has to be a valid account on the server (or in a domain that the server can authenticate against), or else access will be denied. Unless configured to do otherwise, the browser only asks for a user name and password if Bob is not a valid account on the Web server.
      Integrated Windows authentication isn't an Internet standard; rather, it is a proprietary authentication protocol that permits Windows logon credentials to travel over HTTP. Its inner workings haven't been fully documented by Microsoft, although some details have been published by third parties. The details vary somewhat depending on the security provider being used, which can be either NTLM or Kerberos. In essence, however, the client and server negotiate a trust in a series of exchanges that involve user names, domain names, nonces, and hashes.
      Here are the benefits regarding integrated Windows authentication. It provides a better user experience because it doesn't force users who have already logged into Windows to provide a user name and password again. Integrated Windows authentication is secure, even over unencrypted channels, because plain-text passwords are never transmitted.
      There are two negatives to integrated Windows authentication. First, it works in Internet Explorer 2.0 and higher, but is unsupported by other browsers. Second, it's stopped dead in its tracks by most firewalls, primarily because the Windows security protocols that it negotiates—NTLM and Kerberos—rely on ports that are normally sealed off.
      Integrated Windows authentication is a great solution for in-house networks that sit behind firewalls and whose browser clients can be carefully controlled—that is, restricted to Internet Explorer. It is poorly suited for general Internet use.

Getting Information about Authenticated Users

      ASP.NET exposes information about callers via an HttpContext property named User. HttpContext objects accompany each and every request and are exposed to application code through the Context properties of various ASP.NET objects such as Page, WebService, and HttpApplication. Pages (ASPX files) access User through Page.Context.User or simply Page.User.
      User's type is IPrincipal. IPrincipal is an interface defined in the System.Security.Principal namespace that's implemented by the WindowsPrincipal and GenericPrincipal classes. When a user is authenticated using Windows authentication, Page.User refers to a WindowsPrincipal object. When a user is authenticated using another type of authentication, Page.User refers to a GenericPrincipal object. IPrincipal has a method named IsInRole that you can use to test role memberships. (For users authenticated using Windows authentication, roles correspond to groups. For users authenticated using forms authentication, roles do not exist unless they're programmatically assigned.) It also has a property named Identity that exposes information regarding an authenticated user's identity. Identity is actually a reference to an IIdentity interface, which has the members shown in Figure 4.
      It sounds confusing, but in practice, User makes it trivial to get information about callers. If you want to find out whether a caller is authenticated from code in an ASPX file, do this:
if (User.Identity.IsAuthenticated) {
    // The caller is authenticated
      You can also find out whether a caller is authenticated by checking the Request object's IsAuthenticated property, which consults User.Identity.IsAuthenticated under the hood. If you want to know the caller's name (assuming they're authenticated), do this:
string name = User.Identity.Name;

      For a user authenticated using Windows authentication, the name is of the form domainname\username, where domainname is the name of the domain in which the user is registered (or machine name if it's a local account instead of a domain account), and username is the user's name. For forms authentication, the name is normally the one that the user typed into a login form. One use for the user name is to personalize pages for individual users. The application in the next section demonstrates how.

Windows Authentication in Action

      The application in Figure 5, which I'll refer to as CorpNet since it models a simple intranet-type application, uses Windows authentication and ACL authorization to restrict access to some of its pages and to personalize content for individual users. It contains three pages:
  • General.aspx, which provides users with general information about the company
  • Salaries.aspx, which lists the salary of the employee who is viewing the page
  • Bonuses.aspx, which lists this year's employee bonuses
      You'll deploy CorpNet such that anyone in the company can view General.aspx, but only selected individuals can view Salaries.aspx and Bonuses.aspx.
      Before testing can begin, you need to deploy the application on your Web server and configure it to provide the desired level of security. Here are the steps:
  1. Create a directory named Basic, somewhere—anywhere—on your Web server.
  2. Use IIS configuration manager to transform Basic into a virtual directory named "Basic."
  3. While in IIS configuration manager, configure Basic to require basic authentication and to disallow anonymous access. How? Right-click Basic in the IIS configuration manager and select Properties from the ensuing context menu. Go to the Directory Security page of the property sheet that pops up and click the Edit button under "Anonymous access and authentication control." In the ensuing dialog box, uncheck "Anonymous access" and check "Basic authentication," as shown in Figure 6. OK the changes and close the configuration utility.

    Figure 6 Choosing an Authentication Method
    Figure 6 Choosing an Authentication Method

  4. Create two user accounts on your Web server for testing purposes. Name the accounts "Bob" and "Alice." It doesn't matter what passwords you assign, only that Bob and Alice are valid accounts on the server.
  5. Copy General.aspx, Salaries.aspx, Bonuses.aspx, Bonuses.xml, and Web.config to the Basic directory.
  6. Change the permissions on Salaries.aspx so that only Bob and the ASPNET account are allowed access. At the very least, grant them read permission. Other permissions are optional.
  7. Change the permissions on Bonuses.xml (not Bonuses.aspx) to grant access to everyone, but specifically deny access to Alice.
Figure 7 Testing the Application
Figure 7 Testing the Application

      Now give the application a test run by performing the following six exercises:
  1. Type http://localhost/basic/general.aspx into your browser's address bar to call up General.aspx. Because the Basic directory requires callers to be authenticated using basic authentication, a dialog box will pop up. Enter Bob's user name and password. When General.aspx appears, observe that it knows your login name (see Figure 7).
  2. Restart your browser and repeat the previous exercise, but this time enter Alice's user name and password rather than Bob's. General.aspx still displays just fine because both Bob and Alice have permission to access it.
  3. Without restarting your browser, call up Salaries.aspx. Because you're logged in as Alice and Alice isn't allowed to read Salaries.aspx, the server reports that access is denied. (If you're using Internet Explorer, you may have to type Alice's user name and password a few times before being told access is denied.)
  4. Restart your browser and try again to call up Salaries.aspx. This time, log in as Bob when prompted for a user name and password. Because Bob is permitted to read Salaries.aspx, the page comes up and Bob's salary appears. Salaries.aspx is capable of displaying salaries for other employees, too, but it uses the caller's login name to personalize the information that it displays.
  5. Without restarting your browser, call up Bonuses.aspx. A list of employee bonuses appears.
  6. Restart your browser and call up Bonuses.aspx again. This time, log in as Alice. What do you think will happen? Anyone can access Bonuses.aspx, but Bonuses.aspx calls DataSet.ReadXml to read Bonuses.xml, and Alice isn't permitted to read Bonuses.xml. You're logged in as Alice. Will Bonuses.aspx report an error?
      As you can see, Bonuses.aspx comes up just fine and even shows a list of bonuses. Clearly, Bonuses.aspx succeeded in reading Bonuses.xml. How can that happen if Alice lacks permission to read Bonuses.xml? The answer is simple, but also subtle.
      IIS tagged the request with Alice's access token. And it passed that access token to ASP.NET. ASP.NET knows that the caller is Alice and won't allow Alice to retrieve an ASPX file (or any other ASP.NET file type) for which Alice lacks access permission. But because Web.config lacks a statement enabling impersonation, any code executed inside the request executes as ASPNET, not as Alice. ASPNET has permission to read Bonuses.xml, so Alice wasn't prevented from viewing employee bonuses.
      I purposely laid this trap for you to drive home an important point. ASP.NET performs ACL checks on ASPX files and other ASP.NET file types using the caller's identity, regardless of whether impersonation is enabled. That means you can prevent any caller from retrieving an ASPX file simply by denying that caller permission to read the file. However, if a caller pulls up an ASPX file and the ASPX file programmatically reads another file, you must tell ASP.NET to impersonate the caller if you want the reader to be subject to an ACL check using the caller's identity.
      You can prevent Alice from seeing the data in Bonuses.xml by modifying Web.config to read as follows.
    <authentication mode="Windows" />
    <identity impersonate="true" />
The new line turns on impersonating.
      After making the change to Web.config, restart your browser, log in as Alice, and try to view Bonuses.aspx again. This time, you're greeted with an error message reporting that an error occurred while processing the page. That message is displayed by the exception handler in Bonuses.aspx's Page_Load method, which catches the XmlException thrown when ReadXml can't read Bonuses.xml. Restart your browser and log in as Bob, however, and you can once more view Bonuses.aspx.
      CorpNet demonstrates several important principles that you should keep in mind when writing ASP.NET applications that use Windows authentication:
  • Windows authentication is enabled in ASP.NET by including this statement in Web.config.
       <authentication mode="Windows" />
  • ASP.NET applications that use Windows authentication can prevent users from viewing files by using ACLs to deny access to selected security principals.
  • ASP.NET applications that use Windows authentication must enable impersonation if they want resources protected by ACLs to be protected from programmatic accesses by code executed within a request.
  • ASP.NET applications that use Windows authentication can personalize content for individual users by reading user names from Page.User.Identity.Name.
      Remember, too, that ASPX files and other ASP.NET files guarded by ACLs should grant read permission to the account that Aspnet_wp.exe runs as (by default, ASPNET), or else ASP.NET itself can't read the file. In order to prove it, temporarily remove ASPNET from Salaries.aspx's permissions list. Now even Bob can't view Salaries.aspx.

Windows Authentication and URL Authorizations

      CorpNet currently uses ACL authorizations to restrict access to its pages. But ASP.NET also supports URL authorizations. To demonstrate, create a subdirectory named Secret in the Basic directory and move Salaries.aspx, Bonuses.aspx, and Bonuses.xml into it. Then place the following Web.config file in the Secret directory (and be sure to replace domainname with the appropriate machine name or domain name for the Bob account):
      <allow users="domainname\Bob" />
      <deny users="*" />
Log in as Bob and you'll be able to access Salaries.aspx and Bonuses.aspx just fine. But log in as anyone else and it'll be as if the files don't exist.
      The chief drawback to URL authorizations is that they only protect files registered to ASP.NET. You can't use them to protect ordinary HTML files, for example. Another limitation is that URL authorizations are based on stringified names rather than Windows security IDs (SIDs). For these reasons, ACL authorizations are typically used in lieu of URL authorizations when Windows authentication is used, too.

Windows Authentication and Role-based Security

      Role-based security is a powerful concept in Web applications. Rather than restrict access to callers based on user names, role-based security restricts access based on "roles"—CEO, manager, developer, clerk, or whatever—that those users belong to. If you modify the permissions on the Secret directory to only allow access to members of a group named Managers, for example, you're exercising role-based security. Only users that belong to that group can call up Salaries.aspx and Bonuses.aspx.
      Role-based security can also be applied using URL authorizations. The following Web.config file restricts access to the host directory to members of the Managers group. Behind the scenes, ASP.NET handles the chore of mapping the groups to which the caller belongs to roles named in <allow> and <deny> attributes:
      <allow roles="domainname\Managers" />
      <deny users="*" />
      Role-based security applied through URL authorizations suffers from the same limitations as user-based security applied through URL authorizations, and is therefore rarely used outside of forms authentication.


      The marriage between Windows authentication and ASP.NET is a perfect one for intranet sites and also for sites that support Internet access to a controlled population of users. It doesn't, however, map very well to Internet sites that want to serve everybody. Next month, I'll conclude my look at ASP.NET security by taking a close look at forms authentication and seeing how it can be used to secure Web sites without requiring visitors to have logon accounts in your server's domain.
For related articles see:
Security Briefs: ASP .NET Security Issues
Security Briefs Archive
Web Security: Putting a Secure Front End on Your COM+ Distributed Applications
Web Security: Part 2: Introducing the Web Application Manager, Client Authentication Options, and Process Isolation

For background information see:
Security Briefs: Managed Security Context in ASP.NET

Jeff Prosise makes his living programming Windows and teaching others to do the same. He is also a cofounder of Wintellect, a developer training and consulting firm that specializes in .NET developer training. Contact Jeff at This article was adapted from Jeff's upcoming book, Programming Microsoft .NET, which will be published in May 2002 by Microsoft Press.

From the April 2002 issue of MSDN Magazine

Page view tracker