Security


Security and user management have often been seen as quite complicated things 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 other 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, whereby users have Windows accounts, typically used with intranet sites or WAN portals

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

  • Passport authentication, whereby 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\Chapter33\, 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 33-9.

image from book
Figure 33-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.

Check the “Enable roles for this Web site.” option, as shown in Figure 33-10, and click Next.

image from book
Figure 33-10

Then, add some roles, as shown in Figure 33-11.

image from book
Figure 33-11

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

image from book
Figure 33-12

Tip 

In the downloadable code for this chapter, two users are added in this example. The usernames are User and Administrator, and the password for both users is Pa$$w0rd.

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 will 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 33-13.

image from book
Figure 33-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 33-14.

image from book
Figure 33-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.

Open table as spreadsheet

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 location on logging in, VisibleWhenLoggedIn to determine whether the control 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 <RoleGroups> 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 properties are for display formatting, but there are properties such as MailDefinition-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

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

LoginName

This control outputs the username for the currently logged-in user.

CreateUserWizard

This control 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 properties relating to layout formatting, but the default is perfectly serviceable.

ChangePassword

This control enables users to change their passwords. There are three fields, for the old password, the new password, and the confirmation. There are many styling properties.

You will 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 user’s 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 username 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.

Tip 

Note that the configured users for the site are shown on the About page, or you can add your own. The users in the base site (and their passwords) are User1 (User1!!), Admin (Admin!!), and Guest (Guest!!).

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;       DateTime trialDate = 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 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

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