Creating a Very Simple eCommerce Site in asp

advertisement
School of Computing and Engineering
CII 2330 Website Development
Asp.Net with Visual Studio
CII 2330 Website Development
Planning the Site ................................................................................................................................................ 2
Creating a Master Page ................................................................................................................................. 2
Master Page layout..................................................................................................................................... 2
Adding the Master Page ............................................................................................................................. 2
Including a css page. .................................................................................................................................. 3
Applying the MasterPage. .............................................................................................................................. 6
New Files and MasterPage ........................................................................................................................ 6
Navigation .......................................................................................................................................................... 9
Observation .............................................................................................................................................. 11
Creating a User and Log On system ............................................................................................................... 12
Asp.Net Defaults .......................................................................................................................................... 12
Creating a Very Simple eCommerce Site in asp.net ....................................................................................... 14
Adding Tables .............................................................................................................................................. 15
Customers Table ...................................................................................................................................... 15
Orders Table............................................................................................................................................. 16
Products Table ......................................................................................................................................... 16
Images.......................................................................................................................................................... 17
Note .......................................................................................................................................................... 17
OrderLine Table........................................................................................................................................ 18
Creating a page for a New User .................................................................................................................. 18
Simple Search Page .................................................................................................................................... 23
Displaying the Choice ............................................................................................................................... 27
Search By Category......................................................................................................................................... 31
Payment Page .............................................................................................................................................. 36
SqlDataSource1 ....................................................................................................................................... 37
SqlDataSource – InsertIntoOrders ........................................................................................................... 38
SqlDataSource – InsertIntoOrderLine ...................................................................................................... 39
Details.aspx .................................................................................................................................................. 42
Website Administration - Site Security ............................................................................................................ 46
Website Administration - Site Security ............................................................................................................ 46
Admin User .................................................................................................................................................. 46
Creating an Admin Role ............................................................................................................................... 47
Restricting Access to Pages ........................................................................................................................ 47
Security Trimming ........................................................................................................................................ 50
Page 1
CII 2330 Website Development
Planning the Site
You need to load Visual Studio and choose ‘New Web Site’. Browse for a location to store this, it is
recommended you save to a removable storage device, USB stick or removable hard drive.
In the solution explorer, you will see a basic set of files and folders.
It will make life far easier if we can prepare the site and create folders for
assets before we code pages. This can be done later, but any hyperlinks
would need re-establishing.
Right Click on the Site Name
Choose Add Folder
Set up the folders shown here (Admin and Users):
Creating a Master Page
Master pages are used to create a consistent look to all pages in a site, they also have the advantage of
transmitting changes to layout and markup to all pages.
These are often combined with css files.
Master Page layout
For the purposes of this exercise, the master page will have a structure similar to that shown below:
Header
SiteMapPath
Menu
Tree View
Main Page Content
Footer
SiteMapPath, Menu and Tree View are all navigation tools.
Adding the Master Page
Right Click on the site name as before, choose Add New Item and MasterPage (make sure it is not AJAX
MasterPage).
Page 2
CII 2330 Website Development
There will be a section where content can be added in the pages which use the Master Page (a
ContentPlaceHolder), we will not need this for the moment, so delete it.
Including a css page.
A cascading style sheet defines style attributes, you should be familiar with css from previous modules. You
should familiarise yourself with selectors, properties and values and their syntax.
I have one used previously, so I have imported it to the site by right clicking on the site name, choosing
‘Existing Item’ and browsing for the file.
The file can then be dropped on the MasterPage in either source or design view.
Drag and drop the file into
the <head> </head> of the
MasterPage
Next add an html table to the MasterPage (make sure this is html version, not from the standard section of
the toolbar), this is probably best done in source view as shown:
Page 3
CII 2330 Website Development
Next, use your knowledge of html tables to configure this to meet the layout on the previous page.
My version is shown on the next page in split view so you can see how the code matches the design.
Page 4
CII 2330 Website Development
Page 5
CII 2330 Website Development
Next add the required controls from the toolbox as shown:
TreeView
Menu
SiteMapPath
ContentPlaceHolder
The SiteMapPath,Menu and TreeView controls are all found in the Navigation section of the toolbox.
Do not worry about configuring the navigation tools, that will be done at a later stage.
Applying the MasterPage.
It is more common to apply the masterpage when a new page is created, however, this can be added to
existing pages. These is a page called Default.aspx generated with a new site, we will attach the
MasterPage to this:
Open the page in source view
Delete all the code apart from the first line
Amend the first line to include ‘MasterPageFile="~/MasterPage.master"’ as shown below
In design view, right click on the ContentPlaceHolder and choose ‘Create Custom Content’. This creates a
new instance of the ContentPlaceHolder in the aspx page.
New Files and MasterPage
It will also help the creation of navigation tools if we set up the skeleton of pages we will be creating. These
will be empty for the time being.
Open the Admin Folder and right click on it, Choose ‘Add New Item’ and select Web Form, name this
ViewUsers.aspx as shown on the next page:
Page 6
CII 2330 Website Development
Make sure you select ‘Select master page’ you will be prompted as shown:
Repeat for the Default.aspx page :
Page 7
CII 2330 Website Development
In the Users Folder, add the files shown above, again selecting the master page
in all cases, note that Default.aspx appears again, this will be the intro page for
users, the pages act as content holders at the moment, and do not have any
content.
Page 8
CII 2330 Website Development
Navigation
The navigation tolls we will be using a sitemap, this is an xml representation of the structure of the site, we
add a sitemap file to the project by right clicking on the project name, then Add New Item and choose
sitemap, then add.
Keep the default name.
You are presented with this skeleton layout:
Page 9
CII 2330 Website Development
The code between the tags:
<siteMapNode url="" title="" description="">
<siteMapNode url="" title="" description="" />
<siteMapNode url="" title="" description="" />
</siteMapNode>
Represents a single menu item with two sub menu items:
Menu Item 1
Sub Menu Item 1
Sub Menu Item 2
We need to create a sitemap that matches the structure we will use in the project. The following is a
suggestion:
The url is obvious, title is what will appear in the Navigation tool, description becomes the tool tip.
Once the sitemap is set up, it can be applied to the appropriate navigation tool as follows.
Working in the Master Page and
starting with the TreeView control,
open the TreeView Tasks.
Select the dropdown list next to
‘Choose Data Source’ and select
‘New Data Source’
One the next page, choose Site Map, and leave the default ID for the data source.
Page 10
CII 2330 Website Development
The tree view should now update to reflect the site structure:
Repeat for the menu tasks, but choose
SiteMapDataSource1 rather than new data
source.
Experiment with the Views, choose between
and Dynamic.
Static
Observation
These tools allow consistent navigation between pages, but we would not want someone who is not logged
on as an admin user to see the admin menu. This will be dealt with later.
Page 11
CII 2330 Website Development
Creating a User and Log On system
Asp.Net Defaults
The system within Visual Studio used to create uses, and then log them in has various aspects to increase
security. The concept of the authentication and authorization are inter-related to the security features of
Membership and Role Management.
Authentication is a process where-in the identity of the user is determined. Web applications primarily use
Forms Authentication (Intra-net applications could use Integrated Windows Authentication) to verify the
identity of the user using the web application. This is mapped to the membership service in ASP.Net 2.0
Authorization is the next step where the basic aim is to determine whether the authenticated user has
permissions to access the resource. This resource could be a file system or simple .aspx page. Role
Management is the new feature that does the job of authorization in ASP.Net 2.0.
Details of these settings are stored for use in development in the web.config file.
Initially, we will create a basic system using the Visual Studio defaults, and allow the system to create an
SQL database. Later we will look at customising the settings.
Expanding the login section of the toolbox gives the options for creating users,
login and password features.
Go to the NewUser.aspx

Drag an instance of the CreateUserWizard object onto the NewUser web form in design view, this should
go into the content place holder..
Page 12
CII 2330 Website Development
In the properties for the CreateUserWizard1 control, set the to
ContinueDestinationPageUrl to Default.aspx page
Do this by clicking on the button with the 3 dots, and browse for the
file.
Open the Web Form in the Users folder called LoginOK.aspx. In the page, add a label, and set the text
property to something like “Your login was successful”.
Open the Web Form called LogIn.aspx.
Drag a new instance of the Login object onto the LogIn.aspx page in the
ContentPlaceHolder
Set the DestinationPageUrl property to LoginOK.aspx. Do this by clicking
on the button with the 3 dots, and browse for the file.
Go back to Default.aspx. Right click on this in solution explorer, and choose ‘Set as start page’.
It is important that you run the web site and create a new, dummy user. This creates the database and
configures the webconfig file.
If needed, this can be deleted at a later stage through the ASP.Net Configuration tool.
Page 13
CII 2330 Website Development
Creating a Very Simple eCommerce Site in asp.net
You are strongly advised to make back up copies of the site folder at regular occasions, it is possible that
mistakes might mean you are locked out of the database, this would mean you have to restart from scratch.
The first step in this is to amend the standard database created by asp.net and Visual Studio.
Open the Asp.Net configuration wizard
In Security > Select Authentication Type select ‘From the Internet’ as shown.
You can then click done and close down this window
Back in solution explorer, you may need to click refresh, and the
database (ASPNETDB.MDF) should show under App_Data
Page 14
CII 2330 Website Development
Adding Tables
You will see from the screen shot on the right that I have
added four extra tables to the database.
These are:
Customers
Orders
OrderLine
Products
Note
The aspnet_Users table contains the data created from
the CreateNewUserWizard.
Effectively, this has only an ID and password, the
Customers will have more detailed data such as names
and addresses, but must take the ID from aspnet_Users
Set up the tables with the following schema:
This is done by right clicking on Tables, and selecting ‘Add New
Table’.
The primary key for each field can be set by right clicking and selecting the primary key option.
Customers Table
Page 15
CII 2330 Website Development
Orders Table
We will set the OrderId column to start at 1 and automatically update as each new order is created. This is
done in the column properties at the bottom of this section.
Expand ‘Identity Specification’, set the increment (to add 1 to the OrderId field each time a new order is
created), and 1 to seed (so it starts at 1).
Note – TotalCost is DataType decimal
Products Table
Page 16
CII 2330 Website Development
Enter the data shown below you can do this by right clicking on the table name in the server explorer, and
selecting ‘Show Table Data’
Images
You need to collect suitable images from Google Images. Name them P01.jpg .. P012.jpg to match the
description in the table above. E.g. P01.jpg should be a photo of a table, P012.jpg a picture of a ceiling lamp
etc.
These should be placed in the Images folder.
Note
You need to make sure these are all a suitable size for display. Open them in a suitable image package and
change the height and width to something appropriate. In my case height and width are set to 100 pixels for
all the images.
Page 17
CII 2330 Website Development
OrderLine Table
Creating a page for a New User
Go to the NewUser.aspx page.
The ‘CreateUserWizard’ object on the page gives us the standard settings to create a new user. However,
we will need to get extra details from the user (such as First and Last name, address, phone number etc),
and add them to the Customers table in the database.
Expand the options on the wizard, and choose Add/Remove WizardSteps.
Page 18
CII 2330 Website Development
Click ‘Add’ to add a new user step.
Use the arrows to position this step in the middle of the members as
shown.
Set the properties as shown in the
right hand pane of the screenshot.
Then Click ‘OK’
Click the drop down list on the wizard tasks, and choose
‘AddUserDetails’.
In the CreateUserWizard, add an html table and include the following
text, textboxes and SqlDataSource:
txtFirst
txtLast
txtAdd
txtPhone
AddNewUser (this is put in a cell in the table)
txtID
Set the Visible property of txtID to False, we want this to store the UserId data from the aspnet_Users table,
but we do not need to see the value.
Page 19
CII 2330 Website Development
Set the ConnectionString property of the AddNewUser
SqlDataSource object to ASPNETDB.MDF as shown.
Then click on […] in the InsertQuery property.
Click ‘Query Builder’, set up as shown below:
Select the columns as shown
Add the New Values
Click on OK
Page 20
CII 2330 Website Development
Click Add
Parameter,
enter ID
For the first
parameter
‘ID’ Drop
down
Parameter
source,
choose
Session. ID
goes in the
SessionField
.
Click Add
Parameter
for the
remaining
values.
Enter for
each as
shown.
In every
case,
choose
Control for
Parameter
source, and
select the
appropriate
textbox for
each
ControlID
Page 21
CII 2330 Website Development
Open the ‘code behind’ the NewUser page - NewUser.aspx.vb
In the CreateUserWizard1 object go to the FinishButtonClick event, add the following code:
Dim User As MembershipUser
Dim objUser As Object
'Get the username from the previous step in the wizard and store it in the
text box
txtID.Text = (CreateUserWizard1.UserName)
'As the UserName is a uniqueid data type, the following two steps are
needed to store this.
User = Membership.GetUser(txtID.Text)
objUser = User.ProviderUserKey
'Create a session variable, and store the user id in this.
Session("ID") = objUser
'the SqlDataSource inserts the data into the Customers table
AddNewUser.Insert()
'Clears the fields
txtID.Text = ""
txtFirst.Text = ""
txtLast.Text = ""
txtAdd.Text = ""
txtPhone.Text = ""
Essentially, this gets the UserId data which is stored in the aspnet_users table, and stores it in a session
variable called ID.
This is in turn stored in the UserId field of the customers table – this acts as a foreign key to the
aspnet_users primary key.
Note. – Before you test this, you must reset the CreateUserWizard back to the first step – ‘Sign up for your
new account’.
Expand the options on the wizard, and choose ‘Sign Up for Your New Account’ from the Step drop down list.
Page 22
CII 2330 Website Development
Simple Search Page
Note – you must save on a regular basis in this section. Some features will not work unless the code has
been saved.
Open the Search.aspx page
Add the following to the ContentPlaceHolder,
A text box, the ID should be txtProdID
Add a GridView
Add an SqlDataSource
Add a button, Text ‘Search’ ID btnSearch
We need to configure the SqlDataSource, in it’s properties
ad choose Connection String
Click the Drop Down and choose
<New Connection …>
Make sure the Data source is set to Microsoft SQL
Server Database File, and browse for the Database
file name, which is the.ASPNETDB.MDF file in the
App_Data folder of your project.
Test the connection and you should get:
Click OK.
Page 23
CII 2330 Website Development
In properties, choose SelectQuery and click on the … icon (We will use this many times, so take note)
On the next page, select Query Builder, then the Products table from the list
Set up the query builder window as shown:
Click ‘OK’
Click ‘Refresh Parameters’
Page 24
CII 2330 Website Development
Set up the screen as shown below, this will enable the user to search for a product by ID in a parameter
query.
Page 25
CII 2330 Website Development
This will display the results from the search. We now need to select the item returned from the search so
that it can be added to the order.
Expand the GridView tasks
Set the Data Source to SqlDataSource1
Check ‘Enable Selection’
Still in the GridView Tasks, go to ‘Edit Columns’
Page 26
CII 2330 Website Development
In the ‘Selected Fields’
section, highlight ‘Select’
In the CommandField
properties, change
ButtonType to button,
further down the
properties, change
SelectText to ‘Add to
cart’
The GridView should now look like this:
Displaying the Choice
It is useful to display the choice from the search, it will also enable us to provide an easy way to select the
product ID for inserting into the relevant tables.
Place a DetailsView control on the page (not a GridView as previously used). Set the visible property of the
details view control to false also.
Open ‘Choose Data Source’ select ‘new data source’.
Page 27
CII 2330 Website Development
Choose Database from the list as below
Then OK.
Then choose the connection string object.
Page 28
CII 2330 Website Development
Click ‘Next’
Complete the next screen as shown:
You will now have to specify the parameters, Click the WHERE button then set up as shown below:
When this is done Click ‘Add’, the ‘OK’ then ‘Next’ Then ‘Finish’.
Page 29
CII 2330 Website Development
This should display all the record from the item selected from GridView1 (GridView1.SelectedValue)
Add a label to the space above the detailsview control, change it’s ID to lblCart, set the visible property to
false, and the text to ‘Cart Contents’.
These can be changed when an item is selected in the code behind view for the page as:
Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As
System.EventArgs) Handles GridView1.SelectedIndexChanged
lblCart.Visible = True
DetailsView1.Visible = True
End Sub
We need to direct the user to a page where they can enter payment details, and store the selected product in
a session variable so that it can be carried forward to the next page.
Add a button to the page, change the ID to btnPay. Add the following code to the click event by double
clicking on the button:
Protected Sub btnPay_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles btnPay.Click
Session("ProdID") = GridView1.Rows(0).Cells(1).Text
Response.Redirect("~/Users/Payment.aspx")
End Sub
Finally, we need to create a session variable to store the details of the user who has logged on, this will be
needed so that the order can be allocated to the correct customer.
In the page load event of the Search.aspx page add the following:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Dim myUser As MembershipUser
Dim objUser As Object
'As the UserName is a uniqueid data type, the following two steps are
needed to store this.
myUser = Membership.GetUser(User.Identity.Name)
objUser = myUser.ProviderUserKey
'Create a session variable, and store the user id in this.
Session("ID") = objUser
End Sub
Page 30
CII 2330 Website Development
The whole page should look something like:
GridView1
txtProdID
btnSearch
lblCart
DetailsView1
btnPay
Search By Category
This gives the user a different Search option. Open CatSearch.aspx and add the following to the
ContentPlaceHolder:
These are:
2 × GridView
2 × SqlDataSources
1 ×DropDownList
1 × Button, text set to ‘Proceed To Payment’
Page 31
CII 2330 Website Development
Open the tasks for the drop down list and choose Edit Items.
Add items in turn so that the Text Properties reflect the actual category, whilst the Value represents the entry
in the Category column in the Products table.
In the properties window for SqlDataSource1 choose the standard database in the Connection String.
Choose the ‘Select Query’ property open this and choose the Query Builder set this up as shown below.
Page 32
CII 2330 Website Development
Click OK, and select the drop down list from the parameter selector:
Make sure the DataSource in the GridView1 tasks is set to SqlDataSource1.
Also make sure Enable Selection is checked. Set the Selection type to button as described previously.
Page 33
CII 2330 Website Development
In the Task View of the DataGrid1
select ‘Edit Columns’. Add an
ImageField and set the
DataImageUrlField to ImageURL
as shown.
Set the Connection String of SqlDataSource2 to the default database. Open a Select Query, add the
Products table and set up as below:
Page 34
CII 2330 Website Development
Set the Parameters to:
Finally, make sure the Data Source in the GridView2 control is set to SqlDataSource2.
Also Add ProductID to the DataKeyNames Property of both the Grid Views, then add the following code to
the button:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Button1.Click
Session("ProdID") = GridView1.SelectedValue
Response.Redirect("~/Users/Payment.aspx")
End Sub
This will redirect to the Payments page, a description of which now follows:
Page 35
CII 2330 Website Development
Payment Page
Open the page called Payment.aspx
Taking this in stages, add the following to the page:
Details View, leave as the default name
DetailsView1, this displays the order
details
SqlDataSource
txtQuantity
label – lblT_Cost
DropDownList – Set the items to
Mastercard and Visa
txtCardNo
txtSecurityNo
Two sqlDataSources set the ID as
shown
btnConfirm
txtOrderID
SqlDataSource
GridView - grdOrderID
Page 36
CII 2330 Website Development
SqlDataSource1
In the properties:
Set the connection string to the default database.
Click the ‘SelectQuery’ […] button, set up the query builder as shown:
Set up the parameters:
Page 37
CII 2330 Website Development
This will show the order based on the product number resulting from the search, and saved in the session
variable on the previous page.
Set the data source on DetailsView1 to this SqlDataSource.
SqlDataSource – InsertIntoOrders
From the properties panel:
Choose connection string, select the default database.
Click […] in InsertQuery.
In Query Builder, set up:
Note, in the Date column, {fn NOW()} will insert the current date and time,
Page 38
CII 2330 Website Development
Click OK, and set the parameters in the next screen to:
When executed, this sql insert query will put the data into the Orders table, we have set up the properties of
OrderId to automatically start at 1 and increment with each new order.
SqlDataSource – InsertIntoOrderLine
Set the connection
string as before, enter
insert query, in query
builder:
Page 39
an
CII 2330 Website Development
Click OK, in the query builder:
Add these parameters:
Note from above, that the OrderID is obtained from the text box, txtOrderID.
We need to allocate the OrderID to the text box, this initially comes from the Orders table in the database.
Setup the connection string of the SqlDataSource GridSource in the properties as before.
Set up a Select
Query:
This selects the
last OrderId in the
table.
To display this in
the datagrid, set
the Data Source of
the GridView to
GridView.
The value in this
GridView is then
transferred to the
text box in code:
Page 40
CII 2330 Website Development
Double click on btnConfirm to open the code behind window, Payment.aspx.vb. Enter in the following in the
btnConfirm Click event handler.
Protected Sub btnConfirm_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles btnConfirm.Click
Dim T_Cost As Single
T_Cost = Val(txtQuantity.Text) * Val(DetailsView1.Rows(2).Cells(1).Text)
lblT_Cost.Text = T_Cost
If grdOrderID.Rows.Count = 0 Then
Session("OrderID") = 0
txtOrderID.Text = CStr(Session("OrderID") + 1)
Else
Session("OrderID") = Val(grdOrderID.Rows(0).Cells(0).Text)
txtOrderID.Text = CStr(Session("OrderID") + 1)
Session("OrderID") = Val(txtOrderID.Text)
End If
Session("UName") = User.Identity.Name
InsertIntoOrders.Insert()
InsertIntoOrderLine.Insert()
Response.Redirect("~/Users/Details.aspx")
End Sub
Explanation:
The first 3 lines:
Dim T_Cost As Single
T_Cost = Val(txtQuantity.Text) * Val(DetailsView1.Rows(2).Cells(1).Text)
lblT_Cost.Text = T_Cost
Effectively, these lines of code calculate the total cost of the order, this is stored in the variable T_Cost, this
in turn is transferred to the label lblT_Cost.Text property.
The Val function is used to convert the text properties of the textbox and details view to a number.
The next section:
If grdOrderID.Rows.Count = 0 Then
Session("OrderID") = 0
txtOrderID.Text = CStr(Session("OrderID") + 1)
Else
Session("OrderID") = Val(grdOrderID.Rows(0).Cells(0).Text)
txtOrderID.Text = CStr(Session("OrderID") + 1)
Session("OrderID") = Val(txtOrderID.Text)
End If
The purpose of this is to pass the value of the last order number (OrderID) into a session varaible, thyen in
turn into the text box txtOrderID. From here it will be inserted into the OrderLine table, remember we do not
need to do this for the Order table as we have set this up to be generated automatically.
However, the order number in the data grid, grdOrderID is the previous order number, we need to increment
this by 1 to insert it into the OrderLine table.
The first part of the If statement checks to see if the Order table is empty, i.e. no order number present.
Lastly, a new session variable called “UName” has the User name allocated. This is the plain text version,
we already have a session variable called “ID”. However this is the uniqueidentifier data type which is
encrypted.
Page 41
CII 2330 Website Development
Session("UName") = User.Identity.Name
InsertIntoOrders.Insert()
InsertIntoOrderLine.Insert()
Response.Redirect("~/Users/Details.aspx")
The data is inserted into the tables using the sqlDataSource controls and the next page (Details.aspx)
opened.
Details.aspx
This would enable details to be checked, they could be developed using data grids where details could be
edited, however, for this version it is simply displayed using the DetailsView controls. These have the
sqlDataSource controls as DataSources.
DetailsView1
DetailsView2
LoginStatus control
The SqlDataSource controls has the connection string added in the usual way. Also, you should be familiar
with the basic process of setting up Select Queries.
The following 2 screenshots summarise the settings for these controls:
Other features on the page
LoginStatus control – this will allow the user to log out, or redirect them to the login page if they have not
logged in.
Make sure the LogoutPageURL property is set back to Default.aspx, and Logoutaction to ‘Redirect’
Page 42
CII 2330 Website Development
SqlDataSource1 Set the connection string to the default database.
Page 43
CII 2330 Website Development
SqlDataSource2 Set the connection string to the default database
Here, the query builder settings are a little more complex as we need to show data from 3 tables, you need
to add these, then drag and drop links between primary and foreign keys.
The parameter is then set as shown:
Page 44
CII 2330 Website Development
DetailsView1 is allocated SqlDataSource1 as its data source, and DetailsView2 is allocated SqlDataSource2
Page 45
CII 2330 Website Development
Website Administration - Site Security
In asp.net 2, the control over site security has been passed largely from the site administrator or network
manger to the developer of the site.
Most Web sites need to selectively restrict access to certain areas within a web site. Obviously certain
areas/pages will allow the public to come in and browse, however areas that contain more sensitive
information such as Ordering Information, Staff Names, etc. need to allow access only to authenticated
users. (Additionally, you may have personalized areas, akin to site's like My Yahoo!, where you need to the
visitor to be authenticated so that you can generate the customized content specifically for them.)
One of the new features of ASP.NET is Forms Authentication. In classic ASP, where custom database
authentication occurred through the user entering his or her login credentials via an HTML form, ASP.NET
Forms Authentication works similarly. However, many of the mundane tasks and code that you were required
to write in classic ASP are handled for you automatically.
Forms Authentication in ASP.NET is handled by a special FormsAuthentication class. This class contains a
number of static (or Shared) methods that allow you to identify users via a login form. You can easily
configure your ASP.NET application to use Forms Authentication by simply specifying a location (URL) for
your login form - ASP.NET does most of the work from there! When an unauthenticated user visits a
restricted page on your Web site they will be automatically directed to the specified login form. Once they
successfully log on, you can optionally issue an authentication cookie to prevent authenticated users from
having to log in time and time again.
There are two very important features of a Security System that we should formally define.
Authentication - Authentication is the means by which you obtain the Identity of the User by validating their
credentials against a known Authority, ie: Active Directory, Database Store, Microsoft Passport Account etc.
If the credentials can't be validated then the Authentication process fails and the User will assume the
Identity of IUSR_Anonymous. Remember that the Web is anonymous by nature, so they only way to
determine who a particular visitor is to authenticate them by having them provide user credentials (a
username/password, usually). If you have completed the exercises, you will have done this.
Authorization - Authorization occurs after Authentication and involves using information obtained during the
Authentication process to determine whether to grant or deny access to a given resource based on that
Users role in the Application. That is, if you are trying to access a Web page that only a particular user can
access, the first step performed is to authenticate you - who is making the request? - and then, based on that
authentication, you must be authorized to view the particular data you are requesting.
Authorization can be done to some extent through the web.config file, roles can be set via the asp.net
configuration utility. However, a slightly different approach is used here using the code behind each page we
want to restrict access to.
Admin User
First create an admin user, we will have special pages that only they can view, but this type of user cannot
be created using the NewUser.aspx page for obvious reasons.
Open the asp.net configuration utility
Open the Security link
Select Create User
Page 46
CII 2330 Website Development
Enter Admin for username
Select suitable values for the remaining
entries.
Creating an Admin Role
Still in the asp.net configuration utility, security tab. Click on the Create or manage roles link. Create a new
role called ‘admin’.
In Add/Remove users, add the admin user created previously.
Make sure the ‘User Is In Role’ box is ticked:
We will create some admin pages and restrict access to those members of the admin role later.
Restricting Access to Pages
Say we want the following pages to be viewed only if the user is logged in, i.e. has been authenticated:



Search.aspx
Payment.aspx
Details.aspx
We can use methods in the FormsAuthentication class.
Start with Search.aspx, go to the Form Load event handler. There is already code there, this needs
amending.
Page 47
CII 2330 Website Development
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Dim myUser As MembershipUser
Dim objUser As Object
'As the UserName is a uniqueid data type, the following two steps are
needed to store this.
myUser = Membership.GetUser(User.Identity.Name)
objUser = myUser.ProviderUserKey
'Create a session variable, and store the user id in this.
Session("ID") = objUser
End Sub
This needs changing as follows:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If User.Identity.IsAuthenticated = True Then
Dim myUser As MembershipUser
Dim objUser As Object
'As the UserName is a uniqueid data type, the following two steps
are needed to store this.
myUser = Membership.GetUser(User.Identity.Name)
objUser = myUser.ProviderUserKey
'Create a session variable, and store the user id in this.
Session("ID") = objUser
Else
MsgBox("You are not entitled to view this page!",
MsgBoxStyle.Critical, "Warning")
Response.Redirect("~/Default.aspx")
End If
End Sub
This checks to see if the user has logged in – has been authenticated, If
User.Identity.IsAuthenticated = True. If this is the case they get access to the page, if not, a
message box appears and they are redirected to Default.aspx.
Add similar code to Payment.aspx and Details.aspx e.g.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If User.Identity.IsAuthenticated = False Then
MsgBox("You are not allowed to view this page",
MsgBoxStyle.Critical, "Warning")
Response.Redirect("~/Default.aspx")
End If
End Sub
:
Page 48
CII 2330 Website Development
Permissions Based on Roles
Go to the asp.net configuration utility, security tab. Click the ‘Create Access Rules’ link. Set up as shown:
The screen shot is a little indistinct, the Admin folder is selected and the allow permission to this folder is set
for all those users with the role of admin.
There is the facility to make further adjustments to these settings. The asp.net configuration utility will create
a web.config xml file in the admin folder.
Open admin/web.config, it will look like this:
Page 49
CII 2330 Website Development
Add the line shown below:
So all admin users are allowed, all others are denied.
If the user, or casual browser tries to access a page in the admin folder they now get an error:
Security Trimming
It would be better if the navigation controls accessing admin pages were only visible to those logged on with
admin role privileges. This is possible by a method known as Sitemap Security Trimming.
The main implementation for this is in the main web.config file.
Add the following lines:
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
<providers>
<add name="XmlSiteMapProvider"
description="Default SiteMap provider."
type="System.Web.XmlSiteMapProvider "
siteMapFile="Web.sitemap"
securityTrimmingEnabled="true" />
</providers>
</siteMap>
A small addition is now made to the Web.sitemap file:
Add
roles="Admin"
To the end of all lines which include nodes relating to admin pages.
Page 50
Download