Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Build Your Own ASP.NET 2.0 Web Site Using CSharp And VB (2006) [eng]-1.pdf
Скачиваний:
142
Добавлен:
16.08.2013
Размер:
15.69 Mб
Скачать

Chapter 13: Security and User Authentication

Working with Forms Authentication

By far the most popular authentication method, forms authentication is extremely flexible. With forms authentication, you get to choose where the usernames and passwords are stored: in the Web.config file, in a separate XML file, in a database, or in any combination of the three.

Forms authentication is cookie-based—each user’s login is maintained with a cookie. A browser may not access protected pages of the site unless it has a cookie that corresponds to the successful authentication of an authorized user.

You’ll most frequently use three classes from the System.Web.Security namespace as you work with forms authentication:

FormsAuthentication

contains several methods for working with forms authentication

FormsAuthenticationTicket

represents the authentication ticket that’s stored in the user’s cookie

FormsIdentity

represents the authenticated user’s identity

Let’s walk through an example that explains how a basic login page is constructed. We need to take three steps:

1.Configure the authentication mode for the application within the Web.config file.

2.Configure the authorization section to allow or deny certain users within the Web.config file.

3.Create the login page that your visitors will use.

The first step is to configure the authentication mode for the application.

Let’s hand-code an example using the Dorknozzle application. Open it in Visual Web Developer, open the Web.config file, and add the <authentication> tag shown in the following code snippet. Visual Web Developer may already have created an <authentication> tag for you with the default mode of Windows—in this case, just change the value to Forms:

532

Working with Forms Authentication

File: Web.config (excerpt)

<configuration>

<system.web>

<authentication mode="Forms" />

</system.web>

</configuration>

There are four possible values for the mode attribute: Forms, Windows, Passport, and None. Since we’re working with forms authentication, we set the mode to

Forms.

Next, set up the authorization scheme by adding the <authorization> tag:

File: Web.config (excerpt)

<authentication mode="Forms" />

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

</authorization>

As you’ll see in more detail in the next few sections, the question mark symbol (?) represents all anonymous users—that is, users who have not logged in. Essentially, this configuration reads: “Deny all non-logged-in users.” If a user tries to access a page controlled by this Web.config file without logging in, he or she will be redirected to the login page. Unfortunately, this has the side-effect of denying all unauthenticated users access to our style sheet and image files, as well. Thankfully, ASP.NET 2.0 provides a way to override Web.config settings for particular directories of your web site—the location element.

To allow anonymous users access to your App_Themes and Images folders, add the following to Web.config:

File: Web.config (excerpt)

</system.web>

<!-- Allow access to App_Themes directory --> <location path="App_Themes">

<system.web>

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

</authorization>

</system.web>

</location>

<!-- Allow access to Images directory -->

533

Chapter 13: Security and User Authentication

<location path="Images"> <system.web>

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

</authorization>

</system.web>

</location>

</configuration>

Now, all we need do is create that login page.

Create a new page named Login.aspx, which uses a code-behind file, and is based on the Dorknozzle.master master page. Then, modify its title and content placeholders like this:

File: Login.aspx

<%@ Page Language="VB" MasterPageFile="~/DorkNozzle.master" AutoEventWireup="false" CodeFile="Login.aspx.vb" Inherits="Login" Title="Dorknozzle Login" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<h1>Login</h1>

</asp:Content>

If you execute the project now, you’ll notice that no matter which link you click, you’ll be redirected to the blank Login page shown in Figure 13.1.

Naming the Login Page

Note that we didn’t need to specify the name of the login page, Login.aspx, anywhere. By default, unless you specify another form name, ASP.NET will assume that the login page is called Login.aspx.

Authenticating Users

You’re secured. Anonymous users can’t see your application’s pages, and are automatically redirected to the login page. Now what? How do you create users, give them privileges, store their settings, and so on? Well, it depends.

All versions of ASP.NET can store user account data, and details of the resources each user can access, in the Web.config file. However, relying only on the

Web.config file isn’t particularly helpful when the users’ account settings need to be easily configurable: you can’t keep modifying the configuration file to register new users, modify user passwords, and so on.

534

Working with Forms Authentication

Figure 13.1. The Login page

As you probably already suspect, a real user management solution must use the database somehow. Storing authentication and authorization data—such as user accounts, roles, and privileges—in the database gives you much greater flexibility in the long run.

Let’s analyze both possibilities. By the end of the chapter, we’ll have implemented a user authentication and authorization system using the new ASP.NET 2.0 membership features.

Working with Hard-coded User Accounts

Hard-coding user accounts means keeping user data in the code-behind file. This solution should never, ever be used in any application, but it will make things easier for us as we work through the first few examples.

To start off, let’s build a login form that contains a TextBox into which the user can enter a username, another TextBox for the password, and a Button for submitting the data to the server. Add this code after the Login heading in Login.aspx:

535

Chapter 13: Security and User Authentication

File: Login.aspx (excerpt)

<p>Username:<br />

<asp:TextBox id="username" runat="server" /> </p>

<p>Password:<br />

<asp:TextBox id="password" runat="server" TextMode="Password" /> </p>

<p><asp:Button id="submitButton" runat="server" Text="Login" OnClick="LoginUser" /></p>

As you can see, the page contains two TextBox controls, one of which has the TextMode set to Password, which means that an asterisk will display for each character that a user types into this field. The other is a Button control, the OnClick attribute for which calls the LoginUser method. Next, we’ll add the serverside script for this method, which will validate the login credentials. Add the following code to your code-behind file:

Visual Basic File: Login.aspx.vb

Partial Class Login Inherits System.Web.UI.Page

Sub LoginUser(ByVal s As Object, ByVal e As EventArgs)

If (username.Text = "username" And _

password.Text = "password") Then

FormsAuthentication.RedirectFromLoginPage(username.Text, _

False)

End If

End Sub

 

End Class

 

C#

File: Login.aspx.cs

public partial class Login : System.Web.UI.Page+

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void LoginUser(Object s, EventArgs e)

{

if (username.Text == "username" && password.Text == "password")

{

FormsAuthentication.RedirectFromLoginPage(username.Text,

false);

}

}

}

536

Working with Forms Authentication

Execute your project and you’ll see the simple, yet functional, login page shown in Figure 13.2.

Figure 13.2. The simple Dorknozzle Login page

In the code above, the If statement is used to check whether or not the user typed in the correct username and password. If the username and password entered were username and password, respectively, we call the

FormsAuthentication class’s RedirectFromLoginPage method, passing in two parameters.

The first parameter is the username that will be stored in the authentication ticket (the cookie that’s sent to the user’s browser). We’ll simply use the username entered into the form for this example. The second parameter is a Boolean value that indicates whether a persistent cookie should be created. By setting this value to True, you allow your users to close their browsers, open them again, navigate back to your site, and still be logged in to the application. Setting this value to False allows users to be logged in only as long as their browser windows remain

537