Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ASP.NET 2

.0.pdf
Скачиваний:
20
Добавлен:
17.08.2013
Размер:
24.67 Mб
Скачать

Roles and Profiles

Controlling Page Visibility

There may be some situations where you will want to allow a user to know of the existence of a page, even if the user is denied access to it. In this way, you can offer a link to users, but when they click that link, they are prompted to log in as a user with sufficient privileges before they can view the page. In order to achieve this, a roles attribute (see the shaded lines in the following code) can be added to the web.sitemap file, which ensures that a link will be visible to certain users to specified pages, even if the user is unable to view the content of the page itself. As an example:

<siteMapNode title=”Administration” url=”Admin/Admin.aspx” roles=”Reporter,Owner,Manager,Administrator”> <siteMapNode title=”Edit News” url=”Admin/EditNews.aspx”

description=”Edit club news” roles=”Reporter,Owner,Manager,Administrator/>

<siteMapNode title=”Schedule Match” url=”Admin/ScheduleMatch.aspx” description=”Schedule a Match”

roles=”Manager,Owner/>

Notice that the roles attribute on the Admin.aspx page states that Reporters, Owners, Managers, and Administrators should be aware of the existence of the Admin.aspx page. Contrast this with the ScheduleMatch.aspx page, and you’ll see that only Managers or Owners can see the link to be able to schedule matches.

If you log in to the site as ChrisH, you’re a member of the Reporter role, so even if all access to all admin pages is revoked, you will still see links to the Admin.aspx and EditNews.aspx pages, but you won’t see a link to the ScheduleMatch.aspx page.

Because the Web.config file and the roles attributes in the web.sitemap work together to control both visibility and access, the best way to understand how they work together is to see them in an example!

For this Try It Out, make sure you are using the Chapter 11 version of the Wrox United code. The code that has been supplied for this example has been modified slightly for the purposes of this example.

Try It Out

Configuring Visibility, Access, and Authorization

1.First, take a look at the code in the web.sitemap file. This file contains the same code that is used in the live Wrox United application. This is an extract from that file, highlighting the use of the roles attribute:

...

<siteMapNode title=”Fan Club” url=”FanClub.aspx”>

<siteMapNode title=”Add Match Report” url=”FanClub/FanClubMatchReport.aspx” description=”Add a match report”

roles=”FanClubMember” />

<siteMapNode title=”Upload Pictures” url=”FanClub/FanClubPictures.aspx” description=”Upload pictures or video of a match” roles=”FanClubMember” />

</siteMapNode>

...

399

Chapter 11

<siteMapNode title=”Administration” url=”Admin/Admin.aspx” roles=”Reporter,Owner,Manager,Administrator”> <siteMapNode title=”Edit News” url=”Admin/EditNews.aspx”

description=”Edit club news” roles=”Reporter,Owner,Manager,Administrator” />

<siteMapNode title=”Schedule Match” url=”Admin/ScheduleMatch.aspx” description=”Schedule a Match”

roles=”Manager,Owner” />

<siteMapNode title=”Edit Squad” url=”Admin/EditSquad.aspx” description=”Edit the players in the squad” roles=”Owner” />

<siteMapNode title=”Update Score” url=”Admin/MatchScore.aspx” description=”Edit the score for a match in progress” roles=”Reporter” />

<siteMapNode title=”Match Report” url=”Admin/MatchReport.aspx” description=”Upload or edit a match report” roles=”Reporter” />

<siteMapNode title=”Shop” url=”Admin/UpdateProducts.aspx” description=”Update products” roles=”Administrator” />

</siteMapNode>

...

2.The next step is to take a look at the Web.config stored in the root of the Admin folder — notice that no specific locations are defined in this file, hence the only permission currently active on that folder is to deny access to all users:

<?xml version=”1.0” encoding=”utf-8”?> <configuration>

<system.web>

<authorization>

<deny users=”*” /> </authorization>

</system.web>

</configuration>

The result of these two configuration specifications is demonstrated if you run the site and log in, as I have, as ChrisH (password chrish@123). Take a look at Figure 11-14.

I’m a reporter, so I can see the Administration link, and I can see the links to Edit News, Update Score, and Match Report. However, if I click any of those links, I go straight back to the front page of the site — access has been denied!

3.The next step is to allow access to certain resources in the Admin section of the site by role. Open up the Web.config for the Admin folder and add just the following highlighted code:

<?xml version=”1.0” encoding=”utf-8”?> <configuration>

<system.web>

<authorization> <deny users=”*” />

</authorization>

</system.web>

400

Roles and Profiles

Figure 11-14

<location path=”Admin.aspx”> <system.web>

<authorization>

<allow roles=”Reporter,Administrator,Owner,Manager” /> </authorization>

</system.web>

</location>

</configuration>

Log in to the site again as ChrisH and you will now be able to click the Administration link itself and see the Admin.aspx page, shown in Figure 11-15.

The only problem is that you still can’t actually update scores or match reports until you add the remaining permissions.

401

Chapter 11

Figure 11-15

4.Add the following code to complete the Web.config file for the Admin section — and notice that one of the permissions isn’t quite correct:

...

<location path=”Admin.aspx”> <system.web>

<authorization>

<allow roles=”Reporter,Administrator,Owner,Manager” /> </authorization>

</system.web>

</location>

<location path=”EditNews.aspx”> <system.web>

<authorization>

<allow roles=”Reporter,Administrator,Owner,Manager” /> </authorization>

</system.web>

</location>

<location path=”MatchScore.aspx”> <system.web>

402

Roles and Profiles

<authorization>

<allow roles=”Reporter” /> </authorization>

</system.web>

</location>

<location path=”MatchReport.aspx”> <system.web>

<authorization>

<allow roles=”Reporter” /> </authorization>

</system.web>

</location>

<location path=”EditSquad.aspx”> <system.web>

<authorization>

<allow roles=”Owner,Reporter” /> </authorization>

</system.web>

</location>

<location path=”ScheduleMatch.aspx”> <system.web>

<authorization>

<allow roles=”Owner,Manager” /> </authorization>

</system.web>

</location>

<location path=”UpdateProducts.aspx”> <system.web>

<authorization>

<allow roles=”Administrator” /> </authorization>

</system.web>

</location>

<location path=”UserAdmin.aspx”> <system.web>

<authorization>

<allow roles=”Administrator” /> </authorization>

</system.web>

</location>

<location path=”CreateUser.aspx”> <system.web>

<authorization>

<allow roles=”Administrator” /> </authorization>

</system.web>

</location>

</configuration>

In the permissions for the EditSquad.aspx page, notice that the Reporter role has just been granted access. The web.sitemap page hasn’t been modified, so see if you can guess what will be displayed when the page is run! Try it again, logging in as ChrisH once more and see what happens (see Figure 11-16).

403

Chapter 11

Figure 11-16

Here’s the final result — not only can you see the Edit Squad link, but you can actually go to the Edit Squad page and modify members of the squad! Make just one last change to fix this problem. After all, reporters aren’t supposed to be able to modify membership of a team.

5.Open the Admin folder’s Web.config file once more and edit the following highlighted line:

<location path=”EditSquad.aspx”> <system.web>

<authorization>

<allow roles=”Owner” /> </authorization>

</system.web>

</location>

Run the site again, and you will find that if you log in as any of the users who are only members of the Reporters role (ChrisH, John, or ChrisU), you will be able to view the Edit News, Update Score, and Match Report links and page content.

404

Roles and Profiles

6.One last change to make. This time, modify the web.sitemap file as follows:

<siteMapNode title=”Match Report” url=”Admin/MatchReport.aspx description=”Upload or edit a match report” roles=”Reporter” />

<siteMapNode title=”Shop” url=”Admin/UpdateProducts.aspx” description=”Update products” roles=”Administrator, Reporter” />

</siteMapNode>

Now run the page one last time and log in as a Reporter. You will be able to see the link to the Shop page in the Administration section, but if you click the link, you will be taken straight back to the default page!

Before finishing the example, fix this by removing the Reporter role from the SiteMapNode for the UpdateProducts.aspx page.

How It Works

This example highlights the somewhat delicate nature of keeping your web.sitemap and Web.config file data up to date with current business case requirements. If you want to allow users to browse a site anonymously, a common configuration decision is to prompt users when it’s time for them to log in, then display a link that they will want to click but forcing them to authenticate before enabling them to view the page.

In this example, you have seen that the settings for authorization will control which links are available to each user role. The web.sitemap file then can be used to display additional links to a user — links to content that the user doesn’t have permission to access, to indicate that a facility exists (in this case, the Update Products facility in the Admin section) but that the user needs to log in as a sufficiently privileged user before the link will work.

Here’s a look at the most important bits in the code. From the Web.config file for the Admin folder on the site, the shaded lines of code specify that only administrators can add or update products:

<location path=”UpdateProducts.aspx”> <system.web>

<authorization>

<allow roles=”Administrator” /> </authorization>

</system.web>

</location>

Compare this with the addition to the siteMapNode that was made in the last part of the example:

<siteMapNode title=”Shop” url=”Admin/UpdateProducts.aspx” description=”Update products” roles=”Administrator, Reporter” />

This particular combination results in a reporter being able to see a link, but being unable to access the contents of the link.

405

Chapter 11

If the opposite is true, and the authorization level specified in the Web.config file contains more roles than the web.sitemap file, the authorization will take precedence. Hence, when you changed the permissions for the EditSquad.aspx page and logged in as a Reporter, the link appeared in the navigation menu, and the page could be accessed:

<location path=”EditSquad.aspx”> <system.web>

<authorization>

<allow roles=”Owner,Reporter” /> </authorization>

</system.web>

</location>

Working with Roles in Code

Up to this point in the chapter, all of the customization that you’ve looked at has concerned the use of configuration files to lock down access to parts of the site based on user roles. In addition to these techniques, it’s possible to work with roles programmatically in code. This technique has been employed to some extent in the process of applying discounts to shop prices for members of the Fan Club. Many other different methods exist that you can use for working with roles, but the most commonly used is the IsInRole() method.

The following code extract (which you will encounter again in Chapter 13) shows this in action:

Public ReadOnly Property MemberDiscount() As Double

Get

If HttpContext.Current.User.IsInRole(“FanClubMember”) Then

Return SubTotal * MemberDiscountPercentage

Else

Return 0

End If

End Get

End Property

This code resides within the Shopping.vb class file used when users purchase items from the shop. The important piece in this code is the statement that applies the discount to users who are members of the Fan Club, using the User.IsInRole() method call.

The IsInRole() method takes, as an input, a string that is the name of the role to test. As the name of the method suggests, the result will indicate whether or not the user belongs to the role, hence the return value for the method is either true (yes, the user belongs to the requested role) or false (no, the user is not a member of that role). This useful technique is used again as part of the shopping process:

If Context.User.IsInRole(“FanClubMember”) Then

SubTotalLabel.Text = String.Format(“Sub-Total:{0,35:C}”, Profile.Cart.SubTotal)

MemberDiscount.Text = String.Format(“Member Discount:{0:C}”, _

Profile.Cart.MemberDiscount)

DiscountPanel.Visible = True

End If

406

Roles and Profiles

In this extract (from ShoppingCart.ascx.vb), the same test is made. There are slight differences between the two calls. The first employs the HttpContext.Current object:

If HttpContext.Current.User.IsInRole(“FanClubMember”) Then

...

And the second call employs the Context object:

If Context.User.IsInRole(“FanClubMember”) Then

...

You don’t really need to worry about why there is a difference between the two method calls in the context of this chapter, because the actual method that is being called is the same in both cases. However, in case you are of a more inquisitive nature, here’s what’s going on.

In the first case, because the code lives within a separate class file (not a code-beside file for an aspx page or ascx user control), the code could theoretically be called by a different application entirely, outside of the Web environment. When users request a web page, they do so within a context. This context will contain a small amount of information along with each request that the user makes, which is understood by the web server. If the user is anonymous, the server will know that the current context represents an anonymous user; if the user has logged in, this small bit of information indicates that the request has come from an authenticated user. So, the context of a logged-in user states that the request comes from a specific user ID, which ASP.NET can interrogate to find out which roles the user belongs to.

The current context is freely available to web pages and user controls, but classes need to be told a bit more information before they will compile. The actual context that’s being used on the web page is the current context of the HTTP request, hence the class needs to have the HttpContext.Current version of the context, rather than the context that is available to all requests to a web page.

Enabling User Profiles

Enabling roles on a web site is a good way to open up or hide resources to users, and it also provides limited metadata about the users themselves. Just by being a member of the Reporters group, you can assume that John regularly attends matches and submits scores as they happen. However, this is very limited metadata, and it doesn’t give us much more insight into who John is, or what he is interested in. This is where you can start to adopt ASP.NET’s user profiles technology to store more information about a user.

For example, if you are a member of a web site that sells a wide variety of goods, you can buy goods from that site by creating a very basic user profile that validates your e-mail address, and can be used to process and track orders. However, on many shopping sites, you can take this “enrollment” process

much further and supply additional information to your user account and say, “I like products like this.” When you revisit the site, you may then find that the front page changes to show you more items that you are interested in buying, and less of those you’re not so bothered about.

This sort of information can be used to extend a simple user account by creating a user profile for storing this additional information; hence I can specify that I have no interest in owning a PlayStation or Xbox, because I only play games on my PC, and the site will be less likely to show me offers related to PS2 or

407

Chapter 11

Xbox editions of games. Furthermore, the sales team behind the web site may send out targeted e-mails to customers who have expressed an interest in a certain type of product, with the aim of increasing sales.

One of the uses for user profiles is to create areas of a site that are tailored specifically to the currently logged-in user, giving that user a more personalized view of the site. This technique — called personalization — can be used to develop a My Site style area of a web site, where you can amend your own user profile settings, and view information directly relevant to you. In larger corporations, you’ll find that the idea of a personalized area of a web or intranet application is quite commonly used — anyone who has ever used SharePoint Portal Server (or similar Portal-style application) will be familiar with the idea of a My Site area.

As far as SharePoint is concerned, the My Site area of a portal can be highly customized to display your calendar and inbox (linked to an Exchange server), or to store custom lists of links to areas of the portal that you may be interested in. Although you’re not going to build anything as involved as this in this book, SharePoint Portal Server is one of the best examples of personalization I’ve come across, and doubtless the many other Portal-style applications available for purchase will offer similar levels of personalization.

ASP.NET 2.0 has some great tools available for developing simple profiles with relative ease, so in the next section of this chapter, you’ll explore how these tools can be used to customize a site, and you’ll look at how the Wrox United application uses profiles.

Building a Profile

There are two parts to building a profile. The first is to define what items you want to store. The second is to add functionality to a page to both add and edit information in a user profile.

To define which items you want to store in a profile, you add a list of items, and the type of data each item will contain, to the root Web.config file for a site, for example:

<profile enabled=”true”> <properties>

<add name=”MemberName”/> <add name=”Name”/>

<add name=”Address”/> <add name=”City”/> <add name=”County”/> <add name=”PostCode”/>

<add name=”Country”/>

<add name=”Mailings” type=”System.Boolean”/> <add name=”Email”/>

<add name=”Theme”/>

<add name=”Cart” serializeAs=”Binary” type=”Wrox.Commerce.ShoppingCart” allowAnonymous=”true”/>

</properties>

</profile>

408