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

Using the ASP.NET Login Controls

set permissions for individual files in your project, so you’ll either need to place all admin-related functionality into a separate folder (which would allow you to continue using the tool to configure security options), or modify Web.config by hand.

You can set individual access rules for files using the location element, which can contain a system.web sub-element, which, in turn, can contain settings customized for the location. Add this code to your Web.config file:

File: Web.config (excerpt)

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

<system.web>

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

</authorization>

</system.web>

</location>

<!-- Only administrators may access AdminTools.aspx --> <location path="AdminTools.aspx">

<system.web>

<authorization>

<allow roles="Administrators" /> <deny users="*" />

</authorization>

</system.web>

</location>

</configuration>

Now, administrators are allowed to access AdminTools.aspx, as this rule comes first under the authorization element. If you switched the order of the allow and deny elements, no one would be allowed to access AdminTools.aspx.

Now your site is accessible only to authenticated users, with the exception of the administration page, which is accessible only to users in the Administrators role. Now we just need to let users log in into the system.

Using the ASP.NET Login Controls

As we mentioned earlier in this chapter, ASP.NET 2.0 delivers a range of very useful controls related to managing users on your site:

561

Chapter 13: Security and User Authentication

Login

This control displays a login form that contains a User Name text box, a

Password text box, a Remember me next time checkbox, and a Log In button. It’s integrated with the membership API, and performs the login functionality without requiring you to write any code. The layout is customizable through templates and multiple properties.

LoginStatus

This is a simple yet useful control that displays a Login link if the user isn’t logged in; otherwise, it displays a Logout link. Again, this control requires no additional coding in order to work with your application’s membership data.

LoginView

This control contains templates that display different data depending on whether or not the user is logged in. It can also display different templates for authenticated users depending on their roles.

LoginName

This control displays the name of the logged-in user.

PasswordRecovery

If the user has provided an email address and a secret question and answer during registration, this control will use them to recover the user’s password.

ChangePassword

This control displays a form that requests the user’s existing password and a new password, and includes the functionality to change the user’s password automatically, without requiring you to write additional code.

CreateUserWizard

This control displays a wizard for creating a new user account.

Let’s see a few of these controls in action in our own application. In the following pages, we’ll undertake these tasks:

1.Use a Login control in the Login.aspx page to give users a means of logging in to our application.

2.Use LoginStatus and LoginView controls to display Login and Logout links, and ensure that the Admin Tools link is displayed only to site administrators.

562

Using the ASP.NET Login Controls

Authenticating Users

Earlier in this chapter, we created a web form based on the Dorknozzle.master master page, called Login.aspx. Remove the existing controls from the ContentPlaceHolder, and also remove the LoginUser method from the codebehind file.

Using the new ASP.NET 2.0 login controls, we can easily make the authentication work. If you’re using Visual Web Developer, simply drag a Login control from the Login section of the Toolbox to just below the Login header in Login.aspx. If you’d prefer to add the control manually, here’s the code:

File: Login.aspx (excerpt)

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

<h1>Login</h1>

<asp:Login ID="Login1" runat="server"> </asp:Login>

</asp:Content>

If you switch to Design View, you should see a display like the one depicted in Figure 13.15.

Figure 13.15. Using the Login control

Yes, that’s all you have to do! Start your project, and you’ll be sent to the Login page. First, log in with the regular user that you created earlier (not with the admin account), then browse through the links to see that they can indeed be accessed,

563

Chapter 13: Security and User Authentication

with the exception of the Admin Tools link. When you click Admin Tools, you should be sent back to the Login page. This time, log in with the admin user details, and voilà! You’ll gain access to the Admin Tools page as well.

Let’s take a few moments to customize the look of your login controls. Stop the execution of the project, and switch back to Login.aspx in Design View. Select the Login control and click its smart tag to see the three very useful options shown in Figure 13.16.

Figure 13.16. Options for the Login control

The Administer Website link launches the ASP.NET Web Site Administration

Tool. The Convert to Template option transforms the current layout of your control into templates, which you can then customize down to the smallest detail. The

Auto Format… link lets you select a predefined style to apply to this control.

If you were working in a production scenario, I’d advise you to select Convert to Template and use CSS to fine-tune the appearance of your control, as we did with the GridView and DetailsView controls in Chapter 11. However, for the purposes of this exercise, let’s just set the BorderStyle property of the Login control to

Solid, and the BorderWidth property to 1px.

It was simple to add login functionality—we even changed its appearance with just a few mouse clicks! There are just one or two more things that we need to take care of before we can continue to add features to our site. First, let’s deal with personalization.

Customizing User Display

The next feature we want to implement is functionality that gives the user a way to log out of the application. After you perform the changes that we’re about to implement, logged-in users will have the option to log out, as Figure 13.17 illustrates.

On the other hand, users that aren’t logged in won’t see the menu at all, as Figure 13.18 indicates.

564

Using the ASP.NET Login Controls

Figure 13.17. The view that the logged-in user sees

Figure 13.18. The Login page

565

Chapter 13: Security and User Authentication

To implement this functionality, we’ll need to modify the menu in the

Dorknozzle.master master page.

Using Master Pages

At this point, you should appreciate the extraordinary flexibility that master pages offer us. If you didn’t use master pages or web user controls, you’d have to modify all of the pages on your site to implement this new functionality.

Open Dorknozzle.master, and change the code between <!-- Menu --> and <!-- Content --> as indicated here:

File: Dorknozzle.master (excerpt)

<!-- Menu -->

<div class="Menu">

<asp:LoginView ID="loginView" runat="server"> <LoggedInTemplate>

<asp:LoginName ID="loginName" runat="server" FormatString="Hello, {0}!" />

(<asp:LoginStatus ID="loginStatus" runat="server" />)

<asp:SiteMapDataSource ID="dorknozzleSiteMap" runat="server" ShowStartingNode="false" />

<asp:Menu ID="dorknozzleMenu" runat="server" DataSourceID="dorknozzleSiteMap">

<StaticItemTemplate>

<img src="Images/book_closed.gif" border="0" width="16" height="16" alt="+" />

<%# Eval("Text") %> </StaticItemTemplate>

</asp:Menu>

</LoggedInTemplate>

<AnonymousTemplate>

<asp:LoginStatus ID="loginStatus" runat="server" /> </AnonymousTemplate>

</asp:LoginView>

</div>

<!-- Content -->

Also modify the Dorknozzle.css file to accommodate the new control:

File: Dorknozzle.css (excerpt)

.Menu

{

top: 180px;

566

Using the ASP.NET Login Controls

left: 15px; width: 195px;

position: absolute;

}

Don’t let this code scare you; it’s actually quite simple. The root control here is a LoginView control, which displays different templates depending on whether or not the user is logged in (it also knows how to display different templates depending on the roles of the user).

If the site is loaded by an anonymous (unauthenticated) user, we don’t want to display the navigation menu; we want to display only the Login link. The output that’s to be shown to anonymous users by the LoginView control is placed inside its AnonymousTemplate template. There, we use a LoginStatus control that displays a Login link for anonymous users, and a Logout link for logged-in users. Note that with the current Dorknozzle configuration, the contents of the AnonymousTemplate are never actually used—all anonymous users are simply redirected to the login page. However, it’s best to include the LoginStatus control here anyway, just in case we should ever reconfigure the site to include some pages that are accessible to anonymous users.

File: Dorknozzle.master (excerpt)

<AnonymousTemplate>

<asp:LoginStatus ID="loginStatus" runat="server" /> </AnonymousTemplate>

The output that will be displayed to authenticated users is placed inside the

LoggedInTemplate template of the LoginView control. The LoggedInTemplate starts by displaying a welcome message:

File: Dorknozzle.master (excerpt)

<LoggedInTemplate>

<asp:LoginName ID="loginName" runat="server" FormatString="Hello, {0}!" />

By default, the LoginName control displays just the username. However, you can customize it by setting its FormatString property to a custom string, where {0} is a placeholder for the username. Our FormatString value, Hello, {0}! will output “Hello, cristian!” if the user logged in is cristian.

Immediately after this welcome message, we have a Logout link generated by another LoginStatus control, which, as we discussed earlier, displays a Logout link to logged-in users:

567

Chapter 13: Security and User Authentication

File: Dorknozzle.master (excerpt)

(<asp:LoginStatus ID="loginStatus" runat="server" />)

Just below the welcome message and the Logout link sits our old friend, Menu, which displays the navigation menu. Since the Menu is now part of the LoggedInTemplate of the LoginView, it’s displayed only for logged-in users, as we planned.

Finally, it’s worth noting that you can use Visual Web Developer to edit the various templates (and the controls they house). Open Dorknozzle.master in the designer, and click the smart tag of the LoginView control. The options that display, which are shown in Figure 13.19, are certainly interesting.

Figure 13.19. Viewing LoginView Tasks

The Edit RoleGroups… link lets you administer the templates that are shown to users who are assigned particular roles. This facility is useful when you want to display to users specific content that’s relevant to their roles. For example, if you wanted to display to administrators different menus from those that you show to regular users, you could create a group for users within the Users role, and another group for users in the Administrators role, then create different views for these groups using templates.

To check in your code whether or not the current user is authenticated (i.e. logged i n ) , y o u m u s t c h e c k t h e v a l u e o f

HttpContext.Current.User.Identity.IsAuthenticated. To check the role of the logged-in user, you must use the HttpContext.Current.User.IsInRole method, as shown here:

Visual Basic

If HttpContext.Current.User.IsInRole("Administrators") Then

C#

if (HttpContext.Current.User.IsInRole("Administrators"))

{

568