After completing this tutorial, you will be able to
Manage Web-based security
Implement Forms Authentication
Work with Forms Authentication in the raw
Work with ASP.NET login controls to make writing login pages painless
Work with ASP.NET role-based authorization
This tutorial covers managing access to your ASP.NET application. Web site security is a major concern for most enterprises. Without any means of securing a site, the Web site can expose areas of your enterprise you may not want exposed. We'll take a quick look at what security means when it comes to Web applications. Then we'll look at various services available within ASP.NET for authenticating and authorizing users.
¡°Authenticating users¡± means determining a user really is who he or she says (verifying the identity of a user). This is often done using a shared secret such as a password. ¡°Authorizing users¡± means granting or restricting access to a specific user who has identified himself or herself. For example, clients in an administrative role are often granted more access than clients in a role as simple users.
Finally, we'll look at the new login controls, which greatly reduce the amount of development effort you might otherwise put into securing your site.
Software security is a prevalent topic these days, especially with ever increasing public awareness of security issues such as privacy. When a Web application runs on the Microsoft platform, several security issues arise immediately. They include (1) IIS's security context, (2) being sure your clients are who they say they are, and (3) specifying what those clients may and may not do with your application.
Managing Web-based security is similar to managing normal network security in that you still need to manage the authentication and authorization of users. However, Web-based security involves managing clients running different platforms in an open system. That is, you may not have any idea who your site clients are.
While not quite a trivial problem, Windows security is at least a solved problem. Anyone's who's configured a Windows network knows there are myriad issues involved in getting all the users of a network set up appropriately. But a Windows network is a closed system, and everyone on the network is connected and has a baseline level of trust between them (that is, they're all on the network). When you log on to a Windows network, you prove who you are (you authenticate) by providing your user name and password. If the security subsystem believes you are who you say you are, it issues a security token to your Windows session, and every application you start runs with that security token.
The resources (files, folders, drives, applications, etc.) on your computer and on your network are associated with Discretionary Access Control Lists (DACLs). If the security context under which your application runs belongs to a resource's DACL, then you may use it. Otherwise, the system will prevent you from using the resource. This is known as authorization.
In a closed system such as a Windows network, an administrator can effectively survey the whole system and assign users access to various resources. Because it's a closed system, the system can determine very easily whether or not a user belongs in the system and what that user may do.
Contrast this with a Web application. When considering a Web application, you realize first that the range of users of your application is quite wide. They are not necessarily part of your network. That means you need another way (outside of the Windows infrastructure) of authenticating and authorizing the users of your Web application.
Securing IIS
The first security issue you encounter in programming Web applications on the Windows platform is understanding the security context for IIS. Virtually all access to your Web site will be directed through IIS. As with all Windows applications, IIS runs under a specific context. When you install IIS on your machine, the install process creates a separate security identity specifically for IIS.
You can see the identity under which your version of IIS runs by starting the IIS control panel, selecting a virtual directory, right-clicking to get the properties, and then selecting the directory security tab. On my computer, the name of the user is IUSR_D6XXH351, as you can see in Figure 10-1.
Figure 10-1 Managing IIS's authentication settings.
Notice the top left corner of the dialog box includes a check box labeled Anonymous access. When this box is checked, IIS uses the principle identified in the User name field as its security principle. That is, IIS runs with access to the resources as being available for IUSR_D6XXH351.
If you turn off the Anonymous access check box, you may apply Windows authentication to your Web application. In this case, you'd need to give all the potential clients a Windows user name and password. This only works when the clients are running on Windows-based platforms. Users logging on to your site are challenged (meaning they'll be asked to authenticate themselves). They'll see a Windows login dialog box when they log on to your Web site (perhaps you've run into this type of site before). This method of authentication does work well if you're writing an enterprise-wide site and you can count on your audience running Windows-based browsers. However, for a Web site with a wider audience, you'll want to use other means of authentication.
Fortunately, ASP.NET includes Forms Authentication, a straightforward means of authenticating clients. The Forms Authentication subsystem in ASP.NET 1.0 and 1.1 was a huge improvement from having to write your own authentication subsystem. ASP.NET 2.0 includes and improves upon the Forms Authentication model by adding an Authorization subsystem as well.
Let's start by taking a look at Forms Authentication in the raw.
ASP.NET 1.0 and 1.1 introduced a straightforward means of authenticating users. Forms Authentication is driven by an application's Web.Config file. In addition to controlling such aspects as session state, tracing and debugging, and application key-value pairs, Web.Config includes authentication and authorization nodes.
To require users of your site to authenticate, you simply need to place some instructions into your Web.Config file. (You may edit the file directly, or you may use a tool such as the Web Site Administration tool available through Visual Studio.)
Web.Config has a section for specifying how your site should deal with authentication and authorization. In the absence of the authentication and authorization elements, ASP.NET allows unrestricted access to your site. However, once you add these elements to your Web.Config file ASP.NET will force a redirect to a file you specify. Most of the time, the file will be some sort of login page where users must do something such as type in a user name and password.
Before looking at the code, take a look at Figure 10-2, which illustrates how control flows on your Web site when you turn on Forms Authentication using Web.Config.
Figure 10-2 The control flow for a site with Forms Authentication turned on.
To see an example of the most basic authentication you can use in your application, take a look at the files Login.aspx and Web.ConfigFormsAuthentication. The Web.Config includes the Authentication and Authorization elements to support Forms Authentication for the site. Listing 10-1 shows the Web.Config to force authentication.
Listing 10-1
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="login.aspx" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>The login page that goes with it is shown in Listing 10-2.
Listing 10-2
<%@ Page language=C# %>
<html>
<script runat=server>
protected bool AuthenticateUser(String strUserName,
String strPassword) {
if (strUserName == "Gary") {
if(strPassword== "K4T-YYY") {
return true;
}
}
if(strUserName == "Jay") {
if(strPassword== "RTY!333") {
return true;
}
}
if(strUserName == "Susan") {
if(strPassword== "erw3#54d") {
return true;
}
}
return false;
}
public void OnLogin(Object src, EventArgs e) {
if (AuthenticateUser(m_textboxUserName.Text,
m_textboxPassword.Text)) {
FormsAuthentication.RedirectFromLoginPage(
m_textboxUserName.Text, m_bPersistCookie.Checked);
} else {
Response.Write("Invalid login: You don't belong here¡");
}
}
</script>
<body>
<form runat=server>
<h2>A most basic login page</h2>
User name:
<asp:TextBox id="m_textboxUserName" runat=server/><br>
Password:
<asp:TextBox id="m_textboxPassword"
TextMode="password" runat=server/>
<br/>
Remember password and weaken security?:
<asp:CheckBox id=m_bPersistCookie runat="server"/>
<br/>
<asp:Button text="Login" OnClick="OnLogin"
runat=server/>
<br/>
</form>
</body>
</html>This is a simple login page that keeps track of three users¡ªGary, Jay, and Susan. Of course, in a real application this data would come from a database rather than being hard-coded into the page.
In this scenario, even if users try to surf to any page in the virtual directory, ASP.NET will stop them dead in their tracks and force them to pass the login page shown in Figure 10-3.
Figure 10-3 A simple login page for getting a user name and password from a client.
This simple login page authenticates the user (out of a group of three possible users). In a real Web site, the authentication algorithm would probably use a database lookup to see if the user identifying himself or herself is in the database and whether the password matches. Later in this tutorial, we'll see the ASP.NET 2.0 authentication services. The login page then issues an authentication cookie using the FormsAuthentication utility class.
Here's what the Web page looks like in the browser with tracing turned on. Here you can see the value of the Authentication cookie in the cookie collection.
Figure 10-4 Tracing turned on reveals the authentication cookie for a page using Forms Authentication.
Run the Forms Authentication Example
This example shows how to employ Forms Authentication on your site.
To run the Forms Authentication example, create a virtual directory to hold the site. Alternatively, you can use an already existing site and employ Forms Authentication there.
Copy the Login.aspx page from the Tutorial 10 examples into the virtual directory for which you want to apply Forms Authentication.
Copy the Web.ConfigForceAuthentication file from the Tutorial 10 examples into the virtual directory for which you want to apply Forms Authentication. Make sure the configuration file is named Web.Config after you copy it.
Try to surf to a page in that virtual directory. ASP.NET should force you to complete the Login.aspx page before moving on.
Type in a valid user name and password. Subsequent access to that virtual directory should work just fine because now there's an Authentication ticket associated with the request and response.
While you may build your own authentication algorithms, ASP.NET 2.0 includes a number of new features that make authenticating users a straightforward and standard proposition. We'll look at those in a moment.
Briefly, ASP.NET allows two other types of authentication: Passport authentication and Windows authentication. Passport authentication relies upon Passport¡ªa centralized authentication service provided by Microsoft. If you've ever used hotmail.com, you've used Passport. The advantage of Passport authentication is that it centralizes login and personalization information at one source.
The other type of authentication supported by ASP.NET is Windows authentication. If you specify Windows authentication, ASP.NET relies upon IIS and Windows authentication to manage users. Any user making his or her way through IIS authentication (using basic, digest, or Integrated Windows Authentication as configured in IIS) will be authenticated for the Web site. These other forms of authentication are available when configuring IIS. However, for most ASP.NET Web sites, you'll be bypassing IIS authentication in favor of ASP.NET authentication. ASP.NET will use the authenticated identity to manage authorization.
ASP.NET includes a great deal of support for authenticating users (outside of IIS's support). Most of it comes from the FormsAuthentication class.
The FormsAuthentication Class
Many of ASP.NET's authentication services center around the FormsAuthentication class. Listing 10-3 shows the FormsAuthentication class. In the example above, the Login.aspx page uses the FormsAuthentication.RedirectFromLoginPage method to issue an authentication cookie and render the originally requested page. FormsAuthentication includes a number of other services, including issuing an authentication token without redirecting and encrypting passwords.
Listing 10-3
public class FormsAuthentication
{
¡
public static bool CookiesSupported {get;}
public static string FormsCookieName {get;}
public static string FormsCookiePath {get;}
public static string LoginUrl {get;}
public static bool RequireSSL {get;}
public static bool SlidingExpiration {get;}
public static bool Authenticate(string strName,
string strPassword);
public static string Encrypt(FormsAuthenticationTicket ticket);
public static FormsAuthenticationTicket Decrypt(string str);
public static HttpCookie GetAuthCookie(string strUserName,
bool bPersist);
public static string GetRedirectUrl(string strUserName,
bool bPersist);
public static string HashPasswordForStoringInConfigFile(
string strPassword, string strFormat);
public static void RedirectFromLoginPage(string struserName,
bool bPersist);
public static void Initialize();
public static FormsAuthenticationTicket RenewTicketIfOld(
FormsAuthenticationTicket tOld
);
public static void SignOut();
}The example shown in Listings 10-1 and 10-2 show how the rudimentary authentication works by installing an authentication cookie in the response and redirecting the processing back to the originally requested page. There are some other interesting methods in the FormsAuthentication class that allow for finer-grained control over the authentication process. For example, you can authenticate users manually (without forcing a redirect). That's useful for creating optional login pages that vary their content based upon the authentication level of the client.
An Optional Login Page
The code accompanying this tutorial also includes an example showing how to authenticate separately. The page in Listing 10-4 uses the same authentication algorithm (three users¡ªGary, Jay, and Susan¡ªwith hard-coded passwords). However, the page authenticates users and then redirects them back to the same page (OptionalLogin.aspx).
Listing 10-4
<%@ Page language=C# trace="false"%>
<html>
<script runat=server>
protected bool AuthenticateUser(String strUserName,
String strPassword)
{
if (strUserName == "Gary")
{
if(strPassword== "K4T-YYY")
{
return true;
}
}
if(strUserName == "Jay")
{
if(strPassword== "RTY!333")
{
return true;
}
}
if(strUserName == "Susan")
{
if(strPassword== "erw3#54d")
{
return true;
}
}
return false;
}
public void OnLogin(Object src, EventArgs e) {
if (AuthenticateUser(m_textboxUserName.Text,
m_textboxPassword.Text))
{
FormsAuthentication.SetAuthCookie(
m_textboxUserName.Text,
m_bPersistCookie.Checked);
Response.Redirect("optionallogin.aspx");
} else {
Response.Write("Invalid login: You don't belong here¡");
}
}
protected void ShowContent()
{
if(Request.IsAuthenticated)
{
Response.Write("Hi, you are authenticated. <br>" );
Response.Write("You get special content¡<br>" );
} else
{
Response.Write("You're anonymous. Nothing special for you¡ ");
}
}
</script>
<body><form runat=server>
<h2>Optional Login Page</h2>
User name:
<asp:TextBox id="m_textboxUserName" runat=server/><br>
Password:
<asp:TextBox id="m_textboxPassword"
TextMode="password" runat=server/>
<br/>
Remember password and weaken security?:
<asp:CheckBox id=m_bPersistCookie runat="server"/>
<br/>
<asp:Button text="Login" OnClick="OnLogin"
runat=server/>
<br/>
<%ShowContent(); %>
</form></body>
</html>Notice the page sets the authentication cookie manually by calling FormsAuthentication.SetAuthCookie and then redirects the processing back to the page. Each time the page shows, it calls the ShowContent method, which checks the authentication property in the page to decide whether or not to display content specialized for an authenticated user. Because the page redirects manually after authenticating, the Web.Config file needs to look a bit different. To make it work, the authentication node should remain, but the authorization node that denies anonymous users needs to be removed. That way, any user can log in to the OptionLogin.aspx page (they won't be denied) but they may proceed after they're authenticated. Here's the new Web.Config file, shown in Listing 10-5.
Listing 10-5
<configuration>
<system.web>
<authentication mode="Forms">
</authentication>
</system.web>
</configuration>Here's how the optional login page appears before the user has been authenticated, shown in Figure 10-5.
Figure 10-5 The optional login page before an authenticated user logs in.
Run the Optional Login Page
This example shows how to run the optional login page.
To run the optional login page, create a virtual directory to hold the site. Alternatively, you can use an already existing site and try the optional login page from there.
Copy the OptionalLogin.aspx page from the Tutorial 10 examples into the virtual directory.
Copy the Web.ConfigOptionalLogin from the Tutorial 10 examples into the virtual directory. Make sure the configuration file is named Web.Config so ASP.NET picks up on it.
Try to surf to a page in that virtual directory. ASP.NET should allow you to see the page, but as an unauthenticated user.
Type in a valid user name and password. You should see the content tailored for authenticated users. Subsequent requests/responses to and from the site will include an authentication token.
After the user has been authenticated, the optional login page shows the content tailored to the specific authenticated user. Figure 10-6 shows the page after an authenticated user logs in.
Figure 10-6 An Authenticated user has logged in.
So far, you can see that the fundamentals behind employing Forms Authentication are easy to manage. In the examples above, the sites are inaccessible until you prove your identity. The example above shows raw authentication with the users and passwords being hard-coded into the Page file. This is useful for illustration. However, in a real application you'll undoubtedly want to assign user identities to various clients visiting your site.
ASP.NET and Visual Studio include facilities for both managing user identities and for managing roles. The following exercise shows how to set up a secure site in which users are allowed access only after they identify themselves correctly.
Managing User Access
Create a new Web site named SecureSite. Of course, HTTP Web sites using IIS will also have to go through the IIS authentication process.
Open the ASP.NET Administration Tool by selecting Web site | ASP.NET Configuration from the main menu. Go to the Provider tab. Select the Select a single provider for all site management data link. Then select AspNetSqlProvider as the provider, as shown here:
TIP
IIS includes an ASP.NET configuration utility as well. If your site has a virtual directory, you can get to it by opening IIS, selecting the virtual directory of interest, right-clicking to get Properties, and selecting the ASP.NET tab from the configuration dialog.Go to the Security tab. You'll see the page shown in the following graphic. Click the Select authentication type link:
Select From the internet as the access method. This will cause the site to use Forms Authentication.
Select Enable Roles and then select Create or manage roles. Add some roles to the site. The example here includes three roles: Administrator, Joe User, and Power user. Add these roles now. We'll assign real users to them shortly.
Now add some users and assign some roles. From the main security page, select the Create User link. Add some users. You may assign them to roles now if you wish.
After you've added some users and assigned roles to them, Web.Config should look something like this:
<?xml version="1.0"?> <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <system.web> <authorization> <deny users="?" /> <allow roles="Administrator" /> </authorization> <authentication mode="Forms" /> <roleManager enabled="true"/> <compilation debug="true"/></system.web> </configuration>At this point, you may authenticate users to your site. However, you would probably like to control what parts of your site they may access. To do that, create some access rules. Select the Create Access Rules (on security tab) link to manage authorization. Deny anonymous users, as shown in the following graphic:
Denying access to anonymous users causes the following changes in Web.Config.
Notice the authorization and the roleManager elements.
<?xml version="1.0" encoding="utf-8"?> <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <system.web> <authorization> <deny users="?" /> </authorization> <roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider" /> <authentication mode="Forms" /> </system.web> </configuration>Now try running the site. ASP.NET should deny you access to the site, as shown here:

ASP.NET is looking for a way to authenticate the user. However, the site doesn't have one yet. The Forms Authentication setting is set to true, anonymous users are denied access, but there's no instruction to ASP.NET about what to do. There's no login redirect and no login page yet, so ASP.NET simply stops you in your tracks. Let's provide a login page using the ASP.NET login controls.
Earlier in this tutorial, we handcrafted a couple of different login pages. During the heyday of ASP.NET 1.1, that's what you had to do to get Forms Authentication working. ASP.NET 2.0 improves things by adding a number of login controls that perform the most common login scenarios you might need for your site.
These controls include the Login, LoginView, PasswordRecovery, LoginStatus, LoginName, ChangePassword, and CreateUserWizard controls. Here's a summary of what each control does.
Login¡ªThe Login control is the simplest login control and supports the most common login scenario¡ªsigning in using a user name and password. The control includes user name and password text boxes and a check box for users who want to compromise password security by saving their passwords on the machine. The control exposes properties through which you can change the text and appearance of the control. You may also add links to manage registration or password recovery. The Login control interacts with the ASP.NET membership component for authentication by default. If you want to manage authentication yourself, you may do so by handling the control's Authenticate event.
LoginView¡ªThe LoginView control is very like the optional login page mentioned earlier. It's useful for managing the content you display for authenticated versus nonauthenticated users. The LoginView displays the login status via the display templates AnonymousTemplate and LoggedInTemplate. The control renders a different template depending on the status of the user. The LoginView also lets you manage text and links within each template.
PasswordRecovery¡ªThe PasswordRecovery control supports Web sites that send user passwords to clients when they forget their passwords. The control collects the user's account name, and then follows up with a security question (provided that functionality is set up correctly). The control either e-mails the current password to the user or creates a new one.
LoginStatus¡ªThe LoginStatus control displays whether or not the current user is logged on. Nonlogged-in users are prompted to log in, while logged-in users are prompted to log out.
LoginName¡ªThe LoginName control displays the user's login name.
ChangePassword¡ªThe ChangePassword control gives users a chance to change their passwords. An authenticated user may change his or her password by supplying the original password and a new password (along with a confirmation of the new password).
CreateUserWizard¡ªThe CreateUserWizard control collects information from users so it can set up an ASP.NET membership account for each user. Out of the box, the control gathers a user name, a password, an e-mail address, a security question, and a security answer. The CreateUserWizard will collect different information from users, depending on the membership provider used by your application.
The following exercise illustrates how to write a login page using the login controls.
Write a Login Page
ASP.NET wants to see a login page for the SecureSite application called Create a login page. Add a regular Web form to your application. Name the form Login.aspx. Grab a Login control from the toolbox and drag it onto the form, like so:
By applying Forms Authentication through the ASP.NET Configuration tool, ASP.NET understands to use Forms Authentication. The default Login URL is Login.aspx.
Now try to surf to the default page. ASP.NET will now confront you with the login page, like so:
You'll see the default page (provided you logged in successfully):

Authentication is an important step in managing the security of your site. The second half is managing access to your site once users have authenticated themselves. This is known as authorization.
Once you have authenticated a user, you have established his or her identity. While that information is sometimes useful by itself, a system becomes secure when authentication is combined with authorization. Authentication establishes identity, while authorization establishes what users can do when they're signed onto your site.
In the previous example, we added a couple of roles to the site. The following example illustrates how to limit access to certain areas of your site based on the user's identity.
Managing Authorization
Add a folder for Administrators to access. Name the folder Administrators. Add a Web form to the folder that says something like ¡°Administrators Only.¡± Make a JoeUsers folder (and a Web form for Joe Users). Also make a PowerUsers folder and resource.
Now set up associations between the roles you've defined and these new resources. Go to the Web Site Administration tool again. Add some more users, each with various roles assigned. For example, this site includes a user named George associated to the Administrator role, a user named Joe assigned to the Joe User role, and a user named Frodo assigned to the Power User role.
After adding the new users, set up some new access roles. You may do this by selecting the Manage Access Rules link and then selecting the Add New Access Rule link. You may selectively allow or deny various users or classes of users, as shown here:
Add some hyperlinks to the default page so that clients can try to navigate to the various restricted pages.
Now surf to the site. Depending upon which identity you logged in as, you should be allowed or restricted to the various resources.

Table 10-1 shows the users' names and their passwords for the example included with this tutorial.
User Name | Password |
George | abc!123 |
Joe | abc!123 |
Frodo | abc!123 |
This touches upon the utility provided by the login controls. For even more robust login scenarios (including password recovery and optional logins), try some of the other login controls.
In this tutorial we saw the ASP.NET security model. While IIS does have its own security model, leveraging it for Web site security often amounts to giving users to your site a Windows user identity. Perhaps that's okay for a small confined Web site. However, for a site that will be available to potentially the entire globe, that's not such a good thing.
If you decide to let ASP.NET handle authentication, then you have more control over how the authentication happens while at the same time leaving your set of Windows user identities unadulterated. To let a request get past IIS, allow anonymous access to your virtual directory.
Once a request gets past IIS, it's up to ASP.NET to figure out who the user is and how to dole out access. ASP.NET includes an authentication model named Forms Authentication. You turn on Forms Authentication through the Web.Config file. Either use the typing Wizard (that is, type the <authentication > element by hand, or use the Web Site Administration tool (or the IIS ASP.NET tab) to turn on Forms Authentication.
The Web Site Administration tool is useful for adding users, adding roles, and assigning users to roles. It's the most convenient way to manage users and roles. (If you want to, you may set up your own authentication scheme and database, bypassing the ASP.NET support.)
By using ASP.NET Authentication and Authorization support, the Login controls work automatically. The Login controls supply login functionality for the majority of use cases. (As always, you may bypass the support for an authentication and authorization scheme of your own choosing.)
To | Do This |
Use Forms Authentication in your application | 1. Use the ASP.NET Web Site Administration tool (select Web site | ASP.NET Configuration) 2. Use the ASP.NET tab in IIS |
Configure the security aspects of your Web site | 1. Use the ASP.NET Web Site Administration tool (select Web site | ASP.NET Configuration) 2. Use the ASP.NET tab in IIS |
Authenticate a request by hand | Use the FormsAuthentication class's Set Auth cookie |
Invalidate an authentication cookie | Call the FormsAuthentication class's SignOff method |
View the authentication cookie | Turn on tracing |
discuss this topic to forum
