1. Trang chủ
  2. » Công Nghệ Thông Tin

Wrox’s ASP.NET 2.0 Visual Web Develope 2005 Express Edition Starter Kit phần 10 potx

34 381 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Security and Deployment
Trường học Wrox Press
Chuyên ngành Web Development
Thể loại sách
Năm xuất bản 2005
Thành phố Birmingham
Định dạng
Số trang 34
Dung lượng 1,39 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

9 Security and DeploymentIn Chapter 6, we created an administration page, allowing a user to update the menu items, and in Chapter 8, we created the checkout page.. In this chapter, we w

Trang 1

9 Security and Deployment

In Chapter 6, we created an administration page, allowing a user to update the menu items, and

in Chapter 8, we created the checkout page We don’t want everyone to be able to run the administration page, so we need to lock them out somehow For the checkout, it would be good torecognize members of the site and give them the option of having their order added to theiraccount, instead of paying by cash or credit card

The aim is to have a site where users can log in, and have functionality change depending uponwhom they are

In this chapter, we will look at the following:

❑ How security works, and how to configure it

❑ How to add users and roles to a site

❑ How to secure pages

❑ How to change the menu system so that secured pages are not shown on the menu

We will also look at the topic of what to do once you’ve created your first site, and how you cancopy this to a service provider to make the site public Let’s start with the security aspects

Trang 2

You can configure authorization either on a user-by-user basis or by roles, using the Role Manager

service Roles are a way to make configuration easier because you set the configuration for the role andthen you add users to the role This way, if you add or remove users, you only have to add them to therole, rather than changing the configuration You’ll see this in action as we go through the exercises.The configuration of the authorization is done in the Web configuration file, web.config, where we willdefine which pages users can access Let’s give this a go, starting with creating the users

Try It Out Configuring Security

1. In VWD, select the Website menu, and then select the ASP.NET Configuration item This willlaunch the Web Site Administration Tool (see Figure 9-1)

Figure 9-1: The Web Site Administration Tool

2. Select the Security tab, and click the “Use the security Setup Wizard to configure security step

by step” link Step 1 is the welcome step, so click Next

3. On step 2, select the “From the Internet” option, and click Next.

4. Step 3 tells you that the application is configured to use advanced provider settings, so select Next.

5. Step 4 allows the definition of Roles, so tick the “Enable roles for this Web site” option, and

Trang 3

6. You now have an option to define the roles In the New Role Name text box, type Admin and

click the Add Role button No more roles are required, so click the Next button

7. Step 5 allows creation of users, so use the following to create a new user Make sure that theActive User box is ticked, because that ensures the user is active on the site When you’veentered the details, click the Create User button:

Field Text to Enter

Security Question Favorite Pizza

8. When the account is created, click the Continue button, and use the following to add another user:

Field Text to Enter

Security Question Favorite Pizza

9. When the second user has been created, click the Next button

10. Step 6 allows you to add new access rules, restricting pages to selected users This allows security to be added only to folders, but we want individual pages, and we’ll do this manuallylater, so click the Next button

11. Step 7 is the Complete step and tells you that the wizard has been successful, so click the Finishbutton, which will return you to the Security tab, now with the number of users and rolesshown (see Figure 9-2)

Trang 4

12. Click the “Create or Manage roles” link, and select the Manage link alongside the Admin role.

13. On the Search for Users page, click the A link to show users whose name begins with “A.” Tickthe User Is In Role option (see Figure 9-3)

Figure 9-3: Adding a user to a role

14. The users and roles creation is now complete, so close the Web Site Administration Tool

How It Works

All of this work is done by ASP.NET and the Web Site Configuration Tool, so there is no code to examine.However, you must understand what this tool has done, so we’ll start by looking at what additional filesthe tool has added to the site In the Solution Explorer, if you select the App_Datafolder, and click theRefresh button, you’ll see that a new database file base been added, ASPNETDB.MDF(see Figure 9-4)

Figure 9-4: The ASP.NET User and Roles File

This is the database that contains the users and roles, as well as details of which users are in which roles.We’re not going to look at this database, because you don’t really need to know anything about it, justthat it works — ASP.NET handles everything to do with this database for us

You can see the other changes in the Web configuration file, web.config, where the following have been added:

<roleManager enabled=”true” />

<authentication mode=”Forms” />

The first of these, roleManager, simply enables the Role Manager service, so that when users log in,they have roles associated with them If this option is disabled, none of the role-based features will work

Trang 5

You created two users, Daveand Alex, and Alexwas given the Adminrole You’ll soon see how we configure the site so that only users in certain roles can access certain pages.

The second addition, authentication, sets the mode of authenticating users This is set to Forms, whichmeans that a Web form will supply the user credentials (that is, typed by the user on a page) Anothercommon value for this is Windows, which means the user does not have to explicitly enter a user nameand password Instead, the user name used to log in to Windows is used For a public Web site, youshould use Formsauthentication

At this stage, you have only created the users and defined the authentication scheme Now it’s time toconfigure the authorization

Try It Out Securing Pages

1. Run the PPQ application, and when it is displayed in the browser, click the Home link on the menu

2. In the browser address bar, replace Default.aspxwith Admin.aspx(see Figure 9-5) and pressReturn to view the administration page

Figure 9-5: Directly navigating to the Admin page

3. Notice that you haven’t logged in, but that you can navigate directly to this page, even though itdoesn’t appear on the menu Close the browser window

4. Open web.config, and move to the end of the file

5. Between the </system.web>and </configuration>elements, add the following:

Trang 6

Figure 9-6: Navigating to an unauthorized page

7. Close the browser window, and return to VWD.

How It Works

The bulk of the work for securing the admin page is done by the Membership service, but that serviceneeds to know what pages users are allowed to access By default, all users are allowed to access allpages, so you locked down the security by adding a locationelement The locationelement defines

a page by using the pathattribute, and it is this page that further configuration is applied to:

Next, you must stop all other users accessing the page, so you used the denyelement The users

attribute can be a comma-delimited list of users, but you want all users, so the special symbol *is used(this matches any user)

Trang 7

So, the process of authorization is to deny all users but then allow selected users or roles We mentionedearlier that roles are the best way to do this because you only have to configure the security for the roleonce For example, the user Alexis a member of the Adminrole, so Alexwould have access to the

Admin.aspxpage, but Dave, who isn’t in the Adminrole, wouldn’t be able to access the page To allow

Daveaccess, all you have to do is add him to the role; you don’t have to change the configuration.The syntax of the allowand denyelements can take several forms (they are both the same, so we’llshow only allowin the following table:

Configuration Meaning

<allow users=”?” /> Allow all anonymous users An anonymous user is

one who hasn’t logged in

<allow users=”*” /> Allow all users

<allow users=”Alex, Dave” /> Allow only the users Alexand Dave

<allow roles=”Admin” /> Allow only users who are in the Adminrole

You can see that there is quite a degree in flexibility, and to add to that flexibility, you can configureauthorization added at three levels:

❑ For the entire Web site, by using an authorizationelement in the main Web configuration file

❑ For a folder, by placing a Web configuration file in the folder and setting the authorization

as long as one of those roles is Admin, the user will be allowed access to the page

Try It Out Creating the Login Page

1. In the web.configfile, change the authentication section so that it looks like the following:

<authentication mode=”Forms”>

<forms loginUrl=”Login.aspx” />

</authentication>

2. Save the configuration file and close it.

3. Create a new Web form called Login.aspx, remembering to place the code in a separate file,and select the PPQ.mastermaster page

4. Switch the page to Design view, and open the Login section of the Toolbox Drag a Login

control, and drop it into the Content area Select the Auto Format option from the LoginTasks, and select the Simplescheme, before clicking OK to format the control (see Figure 9-7)

Trang 8

Figure 9-7: The formatted Logincontrol

5. Save the file, and switch to Admin.aspx From the right mouse menu, select View in Browser,and notice that instead of the error message, you now see the login page

6. For the user, enter Dave, and for the password enter dave@123 and press the Login button You are returned straight to the login page Enter Alex for the user, and alex@123 for the password.

Press Login and you will see the administration page

Let’s see how this works

When you tried to log in as the user Dave, you weren’t allowed access to Admin.aspxbecause Dave

isn’t a member of the Adminrole Remember, in the earlier exercise you set the authentication, andallowed access only to members of the Adminrole Alexis a member of the Adminrole, so when youlogged in as Alex, you were allowed access to the page

You can see how simple security is, because all you have to do is run the Web Site Administration Tool toset the initial configuration, and add users and roles You then set a few options in the Web configurationfile, and ASP.NET handles everything else for you

Trang 9

Modifying the Menu

One thing that still needs work on the site is usability — you don’t want to force the administrators totype in the Admin.aspxpage name It would be much simpler if the Admin option appeared on themenu, but this means that all users would be able to see it Let’s see how we can add Admin to the menubut have it visible only to authorized users

Try It Out Configuring the Menu

1. Close any browser windows, and return to VWD

2. Open Web.sitemap, and move to the end of the file Underneath the Contactnode, add thefollowing:

<siteMapNode url=”Admin.aspx” title=”Admin” description=”Edit Pizzas” />

3. Save the file and close it.

4. Open PPQ.master, and switch to Design view

5. From the Login section of the Toolbox, drag a LoginStatuscontrol, and drop it underneath themenu (see Figure 9-8)

Figure 9-8: Adding a LoginViewcontrol to the page

6. Save the page and run the application Notice that there is now a Login link under the menu.Click the link, and you are taken to the login page Log in as Dave(the password is dave@123),and see how the Login link now says Logout Also notice that the menu shows the Admin item,even though Dave is not authorized to access the page

7. Click the Admin link on the menu, and notice how the login page is shown once more

8. Close the browser window, and return to VWD

Trang 10

9. From the page-contentfolder, open Web.Config.txt, and copy the contents (the siteMap

<siteMapNode url=”Admin.aspx” title=”Admin” description=”Edit Pizzas” />

You then added a LoginViewcontrol to the master page, and this is a clever control When you are not logged into the site, the LoginViewcontrol shows a Loginlink When you click this link, you areredirected to the login page (the login page you defined earlier in the chapter) with the loginUrl

attribute on the loginelement in the authenticationsection Once you have logged in, the

LoginViewcontrol shows a Logoutlink, which, when clicked, will log you out of the site

You then ran the application and used the LoginViewto log into, and out of, the site, but noticed thatthe Admin link was shown no matter who you logged in as This is because, by default, the menu system doesn’t apply any security To correct that, you modified the Web configuration file, and a

sitemapelement:

<siteMap defaultProvider=”AspXmlSiteMapProvider” enabled=”true”>

<providers>

<clear/>

<add name=”AspXmlSiteMapProvider” type=”System.Web.XmlSiteMapProvider,

System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”siteMapFile=”web.sitemap” securityTrimmingEnabled=”true”/>

</providers>

</siteMap>

You don’t need to know what all of this means, except for the securityTrimmingEnabledattribute,which is the key to the menu security When securityTrimmingEnabledis set to True, the menu system will check the authorization for each page before displaying it When logged in as Dave, themenu system checks each page before showing it, and Daveisn’t authorized to access the Admin page,

so it isn’t shown on the menu Alexis authorized, so the page is shown on the menu

Once again this shows the power of the security system in ASP.NET, and how you can easily add power

to your Web sites with very little effort Let’s now see how we can use the security system from code, tohelp the checkout page

Trang 11

Try It Out Modifying the Checkout Page

1. Open Checkout.aspx, and double-click anywhere on the page, outside of the Contentcontrol.This will open the code file, and create the Page_Loadevent

2. Into the event procedure, add the following code:

If Not Page.IsPostBack Then

If User.Identity.IsAuthenticated ThenDim rbl As RadioButtonList = _DirectCast(Wizard1.FindControl(“RadioButtonList1”), RadioButtonList)rbl.Items.Add(New ListItem(“Charge my account”, “Account”))

End IfEnd If

3. Save the file and run the application.

4. Navigate to the checkout page, and step into the Paymentstep Notice how the paymentoptions list shows only two items

5. Log in to the site Repeat step 4, and notice how there are now three items on the paymentoptions list

Let’s see how this works

How It Works

You added code to the Page_Loadevent, which will run whenever the page is loaded The first linechecks to see if the IsPostBackproperty of the Pageis set If it is, then a button or link on the page hasbeen clicked, and it isn’t the first time the page is loaded If the IsPostBackis not set, then it is the firsttime the page has loaded, so further code is to be run

If Not Page.IsPostBack Then

You then use the Membership service from code, starting with the Userclass, which identifies the current user The Userclass has an Identityproperty, which gives further details about the user, andone of those further details is the IsAuthenticatedproperty If this is set, then the user is authenticated(that is, logged into the site)

If User.Identity.IsAuthenticated Then

Next, you obtained a reference to the RadioButtonListcontrol that shows the payment method

Dim rbl As RadioButtonList = _DirectCast(Wizard1.FindControl(“RadioButtonList1”), RadioButtonList)

You then add a new ListItemto the RadioButtonList, with a Textvalue of Charge my account, and

a Valueof Account

rbl.Items.Add(New ListItem(“Charge my account”, “Account”))End If

End If

Trang 12

That’s all there is to the code When the page first loads, you check to see if the user is logged in ASP.NETprovides a Userobject, which has a property called Identity, and this identifies the user A property ofthe Identity object, IsAuthenticated, tells us whether or not the user has been authenticated (that is, ifthey have logged in) If the user is logged in, you add another option to the list, which you could then use

in the final stage of the payment to charge the user’s account

That’s the end of modifying the pages, so let’s now look at how you can transfer this site to a Web server

Publishing a Site

When using VWD, you have a built-in way to run the Web pages But for live Web sites, you need a lic Web server, and these are managed either by your company or by a service provider To make yoursite available, you need to copy it to the target Web server, and there is a utility provided within VWD tohelp you with it

pub-This utility is available from the Copy Web Site option from the Website menu, which shows theCopy Web page (see Figure 9-9)

Figure 9-9: The initial Copy Web page

Trang 13

To pick the target site, select the “Connect to ” option, which shows the Open Web Site window Youhave the option of copying to a folder, a Web server (Local IIS), an FTP Site, or a Web site using HTTP(Remote Site) Figure 9-10 shows connecting to an FTP site.

Figure 9-10: The Open Web Site page

Once connected, you can see the files from the local site on the left, with the files from the remote site onthe right, and you have options to copy between the two sites For example, Figure 9-11 shows upload-ing files to a remote Web site using the FTP option

Trang 14

Figure 9-11: Uploading files to a Web site

The Copy Web feature allows copying both ways, so if you’ve mistakenly deleted some files from thelocal site, you can always fetch them from the remote site

Summar y

This chapter has covered two major topics: security and deployment

For security, we looked at how you can use the Web Site Configuration Tool to set up security, add users,and set the roles for the users (that is, authentication) We then discussed how to secure Web pages sothat only authorized users can access them, both directly and from a menu This allows you to createpages that only selected users can see, and this aspect, although not covered here, can be extended toparts of a page, so that a page will show different content depending upon the user

You saw that the security system is extremely simple to set up, with only a few configuration optionsrequired to protect a site Not only can you use the security controls to interact with the Membership service but you can also use code This brings added flexibility and becomes more useful as you addmore code to your sites

Trang 15

Finally, we briefly looked at how you can deploy your Web site to a remote location, using the Copy Webtool This allows you to use a variety of methods to copy sites to public Web servers There are otherways to deploy applications, but these aren’t built into the tool The deployment offered in VWD allowsfor a variety of protocols and covers the basics of what you’ll need to deploy to a remote location

In all, we’ve covered a lot of ground in this book, but we have really only scratched the surface of whatASP.NET can achieve You’ve seen how to use databases, how to structure sites using master pages andnavigation, how to view and update data in grids, how to create custom classes, and how to implementsecurity These cover the basics of what you need to construct Web sites and give you good groundingfrom which to continue your exploration of ASP.NET

We hope that you’ve enjoyed this book and that you continue to explore both ASP.NET and Visual WebDeveloper as a means to creating Web sites

Trang 17

Index Index

Symbols

@ (at) symbol, 138

@Pagedirective, 56/* */ (forward slash plus asterisk) symbol, 102–103

~ (tilde) symbol, 56_ (underscore) symbol, 258

Aabstractions (object-oriented programming), 206Access databases (Microsoft), connecting to, 16–17access permissions (Internet Information Services),8–9

accessibility featuresidentifying accessibility needs, 32testing, 63–64

text links, 33Active User box (Security Setup Wizard), 267Add Connection dialog box (Database Explorer, DataConnections), 16–19

Add New Item dialog box (skeleton solution, Web sitemenu)

Master Page, 38–39Web form, 22–23Web User Control, 164Add New Stored Procedure (Stored Procedurescontext menu), 102–103

Add New View option (Views context menu), 104Add ORDER BY clause dialog box, 137–138Add Table dialog box

Database Diagram window, 91Query Editor, 13

Add WHERE clause dialog boxopening the dialog, 134selecting columns for, 135–137Admin role

accessing from menu, 273–274setting up, 267–268

Admin.aspxadding to menu, 273–274creating, 269–270how it works, 270–271uses for, 174, 190Advanced Properties dialog box (Add Connection dialog box), 19

Advanced SQL Generation options dialog box, 175alignment settings (Content Page), 58–59allowelement (web.config file), 271Altproperty (Image control), 45–46AlternateTextproperty (Image control)binding to columns, 120

uses for, 113anchors, target, adding to Master Page, 46–47App_Codefolder (Class Files file), 197AppSettingsproperty (ConfigurationManagerclass), 208

</asp:Content>tags, 62–63ASP.NET 2.0

building web pagesopening a Web site, 20server controls, 23, 48exception handling, 260–262IIS access permission, 8Master Page support, 34navigation controls, 35objects overview, 109–110.aspxpages

Admin.aspxadding to menu, 273–274creating, 269–271function, 174, 190Checkout.aspxadding delivery address form, 239–245adding order confirmation, 248–253adding payment details, 245–248completing the order, 253–254creating, 223, 236

security modifications, 275–276creating, overview, 22–23, 131–133

Ngày đăng: 12/08/2014, 08:22