Site Navigation


The three navigation Web server controls, SiteMapPath, Menu and TreeView, can work with an XML sitemap that you provide for your Web site, or a site map provided in a different format if you implement an alternative site map provider. Once you have created such a data source, these navigation Web server controls are able to automatically generate location and navigation information for users.

You can also use a TreeView control to display other structured data, but it really comes into its own with site maps, and gives you an alternative view of navigation information.

The navigation Web server controls are shown in the following table.

Control

Description

SiteMapPath

Displays breadcrumb-style information allowing users to see where they are in the structure of a site and navigate to parent areas. You can supply various templates, such as NodeStyle and CurrentNodeStyle to customize the appearance of the breadcrumb trail.

Menu

Links to site map information via a SiteMapDataSource control, and enables a view of the complete site structure, appearance customized by templates.

TreeView

Allows the display of hierarchical data, such as a table of contents, in a tree structure. Tree nodes are stored in a Nodes property, with the selected node stored in SelectedNode. Several events allow for server-side processing of user interaction, including SelectedNodeChanged and TreeNodeCollapsed. This control is typically data bound.

To provide a site map XML file for your site you can add a site map file (.sitemap) using the Web site — Add New Item menu item. You link to site maps via providers. The default XML provider looks for a file called Web.sitemap in the root of your site, so unless you are going to use a different provider you should accept the default file name supplied.

A site map XML file contains a root <siteMap> element containing a single <siteMapNode> element, which in turn can contain any number of nested <siteMapNode> elements.

Each <siteMapNode> element uses the attributes shown in the following table.

Attribute

Description

title

Page title, used as the text for links in site map displays.

url

Page location, used as the hyperlink location in site map displays.

roles

The user roles that are allowed to see this site map entry in menus and so on.

description

Optional text used for tooltip pop-ups for site map displays.

Once a site has a Web.sitemap file, adding a breadcrumb trail is as simple as putting the following code on your page:

 <asp:SiteMapPath  Runat="server" /> 

This will use the default provider and the current URL location to format a list of links to parent pages.

Adding a menu or tree view menu requires a SiteMapDataSource control, but again this can be very simple:

 <asp:SiteMapDataSource  Runat="server" /> 

If you are using a custom provider, the only difference is that you can supply the provider ID via a SiteMapProvider attribute. You can also remove upper levels of the menu data (such as the root Home item) using StartingNodeOffset, remove just the top-level link using ShowStartingNode="False", start from the current location using StartFromCurrentNode="True", and override the root node using StrtingNodeUrl.

The data from this data source is consumed by Menu and TreeView controls simply by setting their DataSourceID to the ID of the SiteMapDataSource. Both controls include numerous styling properties and can be themed as you see later in this chapter.

Navigation in PCSDemoSite

The site map for PCSDemoSite is as follows:

 <?xml version="1.0" encoding="utf-8" ?> <siteMap> <siteMapNode url="~/Default.aspx" title="Home"> <siteMapNode url="~/About/Default.aspx" title="About" /> <siteMapNode url="~/MRB/Default.aspx" title="Meeting Room Booker" roles="RegisteredUser,SiteAdministrator" /> <siteMapNode url="~/Configuration/Default.aspx" title="Configuration" roles="RegisteredUser,SiteAdministrator"> <siteMapNode url="~/Configuration/Themes/Default.aspx" title="Themes" roles="RegisteredUser,SiteAdministrator"/> </siteMapNode> <siteMapNode url="~/Users/Default.aspx" title="User Area" roles="SiteAdministrator" /> <siteMapNode url="~/Login.aspx" title="Login Details" /> </siteMapNode> </siteMap> 

The PCSDemoSite Web site uses a custom provider to obtain information form Web.sitemap — necessary because the default provider ignores the roles attributes. The provider is defined in the Web.config file for the Web site as follows:

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">   ...   <system.Web>     ... <siteMap defaultProvider="CustomProvider"> <providers> <add name="CustomProvider" description="SiteMap provider which reads in .sitemap XML files." type="System.Web.XmlSiteMapProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" siteMapFile="Web.sitemap" securityTrimmingEnabled="true" /> </providers> </siteMap>     ... 

The only difference between this and the default provider is the addition of securityTrimming Enabled="true", which instructs the provider to supply data for just those nodes that this current user is allowed to see. This visibility is determined by the role membership of the user, as you see in the next section.

The MasterPage.master page in PCSDemoSite includes SiteMapPath and TreeView navigation displays along with a data source as follows:

  <div >     <h1><asp:literal  runat="server"       text="<%$ AppSettings:SiteTitle %>" /></h1> <asp:SiteMapPath  Runat="server" Css />   </div>   <div >     <div > <asp:TreeView  runat="server" DataSource ShowLines="True" />     </div>     <br />     <br />     <asp:LoginView  Runat="server">       <LoggedInTemplate>         You are currently logged in as         <b><asp:LoginName  Runat="server" /></b>.         <asp:LoginStatus  Runat="server" />       </LoggedInTemplate>     </asp:LoginView>   </div>   <div >     <asp:ContentPlaceHolder  Runat="server" />   </div> </form> <asp:SiteMapDataSource  Runat="server" /> 

The only point to note here is that CSS classes are supplied for both SiteMapPath and TreeView, to facilitate theming.

Security

Security and user management has often been seen as quite a complicated thing to implement in Web sites and with good reason. You have to take a number of factors into consideration, including:

  • What sort of user management system will I implement? Will users map to Windows user accounts, or will I implement something independent?

  • How do I implement a login system?

  • Do I let users register on the site, and if so how?

  • How do I let some users see and do only some things, while supplying some users with additional privileges?

  • What happens in the case of forgotten passwords?

With ASP.NET 2.0 you have a whole suite of tools at your disposal for dealing with questions such as these, and it can in fact take only a matter of minutes to implement a user system on your site. You have three types of authentication at your disposal:

  • Windows authentication, where users have Windows accounts, typically used with intranet sites or WAN portals

  • Forms authentication, where the Web site maintains its own list of users and handles its own authentication

  • Passport authentication, where Microsoft provides a centralized authentication service for you to use

A full discussion of security in ASP.NET would take up at least a full chapter, but there are plenty of things you can look at quickly to get an idea about how things work. You'll concentrate on Forms authentication here, because it is the most versatile system and very quick to get up and running.

The quickest way to implement Forms authentication is via the Website — ASP.NET Configuration tool, which you saw briefly in the last chapter. This tool has a Security tab, and on it a security wizard. This wizard lets you choose an authentication type, add roles, add users, and secure areas of your site.

Adding Forms Authentication Using the Security Wizard

For the purposes of this explanation, create a new Web site called PCSAuthenticationDemo in the directory C:\ProCSharp\Chapter27\, and once the site has been created open the Website — ASP.NET Configuration tool. Navigate to the Security tab, then click the "Use the security setup wizard to configure security step by step." link. Click Next on the first step after reading the information there. On the second step, select "From the internet" as shown in Figure 27-9.

image from book
Figure 27-9

Click Next, and then Next again after confirming that you will be using the default "Advanced provider settings" provider to store security information. This provider information is configurable via the Provider tab, where you can choose to store information elsewhere, such as in a SQL Server database, but an access database is fine for illustrative purposes.

Next, check the "Enable roles for this Web site." option as shown in Figure 27-10 and click Next.

image from book
Figure 27-10

Next, add some roles as shown in Figure 27-11.

image from book
Figure 27-11

Next, add some users as shown in Figure 27-12. Note that the default security rules for passwords (defined in machine.config) are quite strong; there is a 7 character minimum, including at least 1 symbol character and a mix of uppercase and lowercase.

image from book
Figure 27-12

On the Next tab you can define access rules for your site. By default, all users and roles will have access to all areas of your site. From this dialog you can restrict areas by role, by user, or for anonymous users. You can do this for each directory in your site, because this is achieved via Web.config files in directories as you see shortly. For now, skip this step, and complete authentication setup.

The last step is to assign users to roles, which you can do via the Manage users link on the Security tab. From here you can edit user roles, as shown in Figure 27-13.

image from book
Figure 27-13

Once you have done all this, you're pretty much there. You have a user system in place, as well as roles and users.

Now you have to add a few controls to your Web site to make things work.

Implementing a Login System

If you refresh the Solution Explorer display after running the security wizard you'll see that a Web.config file has been added to your project with the following content:

 <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <roleManager enabled="true" /> <authentication mode="Forms" /> </system.web> </configuration> 

This doesn't seem like a lot for the work you've put in, but remember that a lot of information is stored in a SQL Express database, which you can see in the App_Data directory, called ASPNETDB.MDF. You can inspect the data that has been stored in this file using any standard database management tool, including Visual Studio. You can even add users and roles directly to this database if you are careful.

By default, logging in is achieved via a page called Login.aspx in the root of your Web site. If users attempt to navigate to a location that they don't have permission to access, they will automatically be redirected to this page and returned to the desired location after successfully logging in.

Add a Web Form called Login.aspx to the PCSAuthenticationDemo site and drag a Login control onto the form from the toolbox.

This is all you need to do to enable users to log in to your Web site. Open the site in a browser and navigate to Login.aspx; then enter the details for a user you added in the wizard, as shown in Figure 27-14.

image from book
Figure 27-14

Once you have logged in, you will be sent back to Default.aspx, currently a blank page.

Login Web Server Controls

The Login section of the toolbox contains several controls, as shown in the following table.

Control

Description

Login

As you have seen, this control allows users to log in to your Web site. Most of the properties of this control are for styling the supplied template. You can also use DestinationPageUrl to force redirection to a specific loca- tion on logging in, VisibleWhenLoggedIn to determine whether the con- trol is visible to logged in users, and various text properties such as CreateUserText to output helpful messages to users.

LoginView

This control enables you to display content that varies depending on whether users are logged in, or what roles users are in. You can put content in <AnonymousTemplate> and <LoggedInTemplate>, as well as <Role Groups> to control the output of this control.

PasswordRecovery

This control enables users to have their password mailed to them, and can use the password recovery question defined for a user. Again, most proper- ties are for display formatting, but there are properties such as Mail Definition-Subject for configuring the e-mail to be sent to the user's address, and SuccessPageUrl to redirect the users after they have requested a password.

LoginStatus

Displays a Login or Logout link, with customizable text and images, to users depending on whether they are logged in.

LoginName

Outputs the username for the currently logged-in user.

CreateUserWizard

Displays a form that users can use to register with your site and be added to the user list. As with other login controls, there are a large number of prop- erties relating to layout formatting, but the default is perfectly serviceable.

ChangePassword

Enables users to change their passwords. There are three fields, one for the old password, and two for new password and confirmation. There are many styling properties.

You see some of these in action in PCSDemoSite shortly.

Securing Directories

One final thing to discuss is how to restrict access to directories. You can do this via the Site Configuration tool as noted earlier, but it's actually quite easy to do this yourself.

Add a directory to PCSAuthenticationDemo called SecureDirectory, as well as a Default.aspx Web page in this directory, and a new Web.config file. Replace the contents of Web.config with the following:

<?xml version="1.0" ?> <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">   <system.web> <authorization> <deny users="?" /> <allow roles="Administrator"/> <deny roles="User" /> </authorization>   </system.web> </configuration>

The <authorization> element can contain one or more <deny> or <allow> elements representing permission rules, each of which can have a users or roles attribute saying what the rule applies to. The rules are applied from top to bottom, so more specific rules should generally be near the top if the membership of rules overlaps. In this example, ? refers to anonymous users, who will be denied access to this directory, along with users in the User role. Note that users in both the User and Administrator roles will only be allowed access if the <allow> rule shown here comes before the <deny> rule for the User role — all of a users' roles are taken into account, but the rule order still applies.

Now when you log in to the Web site and try to navigate to SecureDirectory/Default.aspx you will only be permitted if you are in the Admin role. Other users, or users that aren't authenticated, will be redirected to the login page.

Security in PCSDemoSite

The PCSDemoSite site uses the Login control you've already seen, as well as a LoginView control, a LoginStatus control, a LoginName control, a PasswordRecovery control, and a ChangePassword control.

One difference is that a Guest role is included, and one consequence of this is that guest users shouldn't be able to change their password — an ideal use for LoginView, as illustrated by Login.aspx:

 <asp:Content  ContentPlaceHolder Runat="server"> <h2>Login Page</h2> <asp:LoginView  Runat="server"> <RoleGroups> <asp:RoleGroup Roles="Guest"> <ContentTemplate> You are currently logged in as <b> <asp:LoginName  Runat="server" /></b>. <br /> <br /> <asp:LoginStatus  Runat="server" /> </ContentTemplate> </asp:RoleGroup> <asp:RoleGroup Roles="RegisteredUser,SiteAdministrator"> <ContentTemplate> You are currently logged in as <b> <asp:LoginName  Runat="server" /></b>. <br /> <br /> <asp:ChangePassword  Runat="server"> </asp:ChangePassword> <br /> <br /> <asp:LoginStatus  Runat="server" /> </ContentTemplate> </asp:RoleGroup> </RoleGroups> <AnonymousTemplate> <asp:Login  Runat="server"> </asp:Login> <asp:PasswordRecovery  Runat="Server" /> </AnonymousTemplate> </asp:LoginView> </asp:Content> 

The view here displays one of several pages:

  • For anonymous users a Login and a PasswordRecovery control are shown.

  • For Guest users LoginName and LoginStatus controls are shown, giving the logged-in user name and the facility to log out if required.

  • For RegisteredUser and SiteAdministrator users LoginName, LoginStatus, and ChangePassword controls are shown.

The site also includes various Web.config files in various directories to limit access, and the navigation is also restricted by role.

Note

Note that the configured users for the site are shown on the about page, or you can add your own.

One point to note here is that while the root of the site denies anonymous users, the Themes directory (described in the next section) overrides this setting by permitting anonymous users. This is necessary because without this, anonymous users would see a themeless site, because the theme files wouldn't be accessible. In addition, the full security specification in the root Web.config file is as follows:

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">   ... <location path="StyleSheet.css"> <system.web> <authorization> <allow users="?"/> </authorization> </system.web> </location>   <system.web> <authorization> <deny users="?" /> </authorization> ...   </system.web> </configuration>

Here a <location> element is used to override the default setting for a specific file specified using a path attribute, in this case for the file StyleSheet.css. <location> elements can be used to apply any <system.web> settings to specific files or directories, and can be used to centralize all directory-specific settings in one place if desired (as an alternative to multiple Web.config files). In the preceding code, permission is given for anonymous users to access the root style sheet for the Web site, necessary because this file defines the layout of the <div> elements in the master page. Without this, the HTML shown on the login page for anonymous users would be difficult to read.

Another point to note is in the code-behind file for the meeting room booker user control, in the Page_Load() event handler:

void Page_Load(object sender, EventArgs e) {    if (!this.IsPostBack)    { nameBox.Text = Context.User.Identity.Name;       System.DateTime trialDate = System.DateTime.Now;       calendar.SelectedDate = GetFreeDate(trialDate);    } }

Here the username is extracted from the current context. Note that in your code-behind files you will probably also use Context.User.IsInRole() frequently to check access.




Professional C# 2005
Pro Visual C++ 2005 for C# Developers
ISBN: 1590596080
EAN: 2147483647
Year: 2005
Pages: 351
Authors: Dean C. Wills

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net