Title: Configuring an ASP'NET Application
1Configuring an ASP.NET Application
- Introduction to ASP.NET
- By Kathleen Kalata
2Objectives
- In this chapter, you will
- Learn how to maintain state in an ASP.NET
application - Identify the configuration files used in an
ASP.NET application - Create a Web page that maintains state using an
HTTP cookie - Create a Web page that maintains state without
using HTTP cookies - Implement the security methods used in ASP.NET
3Web Application Benefits
- A Web application is a group of files and folders
(including virtual folders) located under the Web
applications root directory - Create application-level and session-level
variables that are available to all pages within
the Web application - A Web application runs in its own memory space,
so that an error in one Web application does not
bring down the rest of the Web applications on
your server - Maintains information about your session, such as
your IP address, what pages you clicked and when,
when you visited the site, what browser you are
using, and your preferences - Maintains information across the entire Web
application with the application object
4Sessions
- User information can be tracked across user
sessions and across the entire application - HTTP headers using the ServerVariables collection
- SessionID, a unique identifier that identifies
each session - You need only one identifier such as login ID or
IP address - then all previous session data can
be retrieved - UsersTable - UserID and password fields
- SessionData Table - information gathered from
each session - UserID field - links between the tables
5Storing User Session Data
- This memory space is referred to as an isolated
process and is separate from the process that
contains the IIS Web server
6Privacy Policies
- A privacy policy is often used to inform the user
about the type of information that is being
collected and about what is being done with that
information - Web sites that discuss privacy issues and privacy
policies - TRUSTe (http//www.truste.org/)
- Electronic Frontier Foundation (http//www.eff.org
/) - Life Beyond Yahoo (http//www.lifebeyondyahoo.com/
life/privacy.asp) - Privacy.Net (http//www.privacy.net/)
7Application Configuration Files
- A Registry is where Windows applications
typically store their configuration settings - The Metabase stored most of the Web application
configuration data - To access the Metabase
- Internet Service Manager (ISM) local
application - Windows Scripting Host (WSH) - creates scripts
- HTMLA a remote administration Web site
8Internet Service Manager
9View the IIS Property Pages
- Web Site Tab - contains configurations that
identify the Web site IP address and TCP port - simultaneous connections
- application timeout
- keep-alives property - to maintain state with
HTTP 1.1 - The W3C Extended Log File Format - extended
properties such as Client IP Address, the User
Name, Method, HTTP Protocol Version, User Agent,
Cookie, and Referrer - default location Web server log files
WinDir\System32\LogFiles - default directory - is W3SVC1
- log filename - is named after the date
10Web Site Property Sheet
11The Default Extended Logging Properties
12Home Directory Tab
- Configure the Web site location
- Read property - allows visitors to read the Web
page - Directory browsing property - allows you to see
the contents of a folder - Log visits property - will allow the log file to
log visits to the Web site - Index this resource property - will enable Index
Server to include this Web resource
13Home Directory Tab
- Write property - allows editors to publish to the
Web site using the HTTP Put - Script source property - allows visitors access
to your script source code - Execute permissions run executable files
- Scripts permission - allows you to read the
resource and execute the scripts
14Other Tabs
- HTTP Headers Tab - allows you to enable content
expiration - Custom Errors Tab - configures your own custom
error pages within IIS - Performance Tab - allows you to tune the Web
server performance based on the number of
expected hits per day - Directory Security Tab - enables anonymous
access, basic authentication, or Windows
authentication
15Web Server Configuration Files
- XML-based
- Global machine-level configuration file - named
machine.cfg located in C\WINNT\Microsoft.NET\Fram
ework\v1.0. 3705\CONFIG\machine.config - Application configuration files - named
Web.config - About thirty configuration settings configured as
a node, and may include nested child nodes - root node - of the file is ltconfigurationgt
- ConfigSections node - is used to identify the
configuration sections and section groups - system.web section group - delineates Web
configuration settings
16Pages Configuration Node
- Allows you to configure settings that control how
content is delivered to the Web page - Buffer is an area in memory on the server
- enableSessionState allows you to use the Session
capabilities of ASP.NET - enableViewState is used to store data in the
_VIEWSTATE hidden form field in the Web page - enableViewStateMac is used to validate data using
a one-way authentication code based on the MAC
address of the server - autoEventWireup allows you to override the
Page_OnLoad event
17The httpRuntime Configuration Node
- Properties
- executionTimeout is the time that a resource is
allowed to execute before the request times out - maxRequestLength is the number of kilobytes that
can be accepted from an HTTP request - UseFullyQualifiedRedirectURL property is used to
fully qualify the URL when the client has been
redirected to a new page
18The AppSettings Configuration Node
- To configure custom key/value pairs known as
application variables - ltappSettingsgt
- ltadd key"SN" value"Tara Store" /gt
- ltadd key"CS" value"ProviderMicrosoft.Jet.OLEDB.
4.0 - Password''
- User IDAdmin
- Data Source
- C\Inetpub\wwwroot\Ch8\TS.mdb" /gt
- lt/appSettingsgt
19Globalization Configuration Node
- Responsible for setting the encoding standard
used for incoming requests and outgoing responses
- Unicode character set - each unique character set
has its own identity - UTF8Encoding class is contained within the
System.Text namespace and the default value for
encoding is UTF-8 - UTF-8 stands for UCS Transformation Format, 8-bit
form, which means that all Unicode character
values are supported - code page property - also represents the encoding
values, code page for UTF-8 is 65001
20Globalization Configuration Node
- requestEncoding property - configures the
encoding of incoming requests - responseEncoding property - configures the
encoding of outgoing responses - Culture and uiCulture properties are used to
identify a language and culture string - en-GB for British English
- en-IE for Irish
- fr-FR for French
- en-US for United States English
21Configuring the Globalization Application
Settings
22Compiler Node Configuration
- Settings related to the language compilers use to
build the application - defaultLanguage property changes the default
compiler from Visual Basic .NET - lt_at_ Page Language"vb"gt
- debug property is used to configure the
application to show the source code files when
you are debugging the application - explicit property requires you to declare your
variables before they are used - strict property requires you to declare the data
type of a variable before it is used
23Trace Node Configuration
- Identify the data sent during a request or
response. - Trace"true" in the _at_Page command.
- enabled property - allows the application to turn
tracing on - localOnly property - results are only displayed
to the localhost at http//localhost/. - traceMode property - allows you to sort trace
results based on time using SortByTime or by
category using SortByCategory - pageOutput property - allows you to display the
trace results with the Web page - trace utility program - access the tracing data
stored in memory using TraceTool - requestLimit property - number of trace results
stored
24Trace Node Configuration
- Located at http//localhost/approot/Trace.axd or
at localhost/Configuration/Tracing/TraceTool/trace
.axd - Trace.write
- to write data to the trace stack
- trace.write("CategoryName", "Value") method
- CategoryName - a string that contains the text
label to be displayed in the trace output - value - a string that contains the data and
appears in the Message column
25CustomErrors Node Configuration
- To configure error messages
- Both ASP.NET and IIS provide error pages that
describe the error - The IIS Web pages are located in the
c\winnt\Help\iisHelp\common\ directory - IIS uses the Internet Service Manager tool to
configure custom error pages - HTTP status message code - indicates the status
of the request - 200 - success
- 404 - file requested could not be found
- 400s usually indicate a client-related error
- 500s usually indicate a server-related error
26Configuring Error Pages Using the Internet
Services Manager
27CustomErrors Node Configuration
- Properties
- RemoteOnly - rich error pages are only displayed
locally - On - application contains custom error pages
except for at localhost - Off - ASP.NET error pages are displayed
- defaultRedirect property - which sets a default
error page to be displayed if no applicable
custom error page is configured - error node uses the statusCode property to
catch the status message and the redirect
property to redirect the user when the error is
detected
28Maintaining State in an ASP.NET Application
- Three methods that use a unique identifier to
recognize the client across Web pages - Client-side cookies - small files stored on the
clients system - ASP.NET uses Application and Session objects -
store data and require session support - Cookieless applications applications do not
require the user to support client-side or
server-side cookies as the identification data is
passed with the URL. Stores the data with the
request
29Client-side Cookies
- A client-side cookie is a small piece of
information that is stored on a clients local
computer - The Cookies collection is a group of cookies that
are sent by the server through the header to the
client - The browser application on the client receives
the cookie and writes the cookie to the clients
file system - The cookie file, whether its from Netscape or
Internet Explorer, stores the name of the cookie,
the value, and the name of the server that wrote
the cookie
30Client-side Cookies
- In Internet Explorer, each cookie is stored in a
separate text file. In Windows 2000, Internet
Explorer stores cookies in C\Documents and
Settings\UserID\Cookies
31Reading and Writing Client-sideCookies Using
JavaScript
- The cookie property of the document object allows
you to store client-side cookies and read
client-side cookies associated with the document - If you plan to use client side cookies, each
cookie name and value pair is separated by a
semicolon
32HTTP Cookies
- HTTP cookies are cookies created by the Web
server rather than the browser - The SessionID is the value of the HTTP cookie
that identifies the clients session - This SessionID is used to identify a Session
object on the server - Retrieve a cookie from the HTTP header using the
server variable HTTP_COOKIE from a Web page using
the server variables that has Trace enabled
33HTTP Cookies
- Internet Explorer 5 - users can disable client
side cookies, and still allow HTTP cookies. - Internet Explorer 6 - the cookie settings have
been moved from the Security settings to a
Privacy Settings
34Creating Cookies with ASP.NET
- The HttpCookieCollection object represents the
cookie variables - One type of cookie collection contains cookies
that have been generated on the server and
transmitted to the client in the Set-Cookie
header - The Response.Cookies method actually sends the
cookie to the browser, which in turn writes the
cookie to the clients file system - The named group of cookies is also referred to as
a dictionary cookie, and the individual cookies
within it are sometimes referred to as cookie keys
35Creating Cookies with ASP.NET
- Retrieve a cookies valuewhether from a simple
cookie or from a group of cookiesusing the
Request object - lt Request.Cookies(CookieName) gt
- To retrieve the value of a single cookie from a
group of cookies, you must identify the name of
the cookie group as well as the name of the
individual cookie - lt Request.Cookies("GroupID")(CookieName_n) gt
- You can add additional cookies to the HTTP
cookies - Dim MyCookie As New HttpCookie("CookieEmail")
- MyCookie.Value txtEmail.Value
- Response.Cookies.Add(MyCookie)
36Create a Page that uses HTTP Cookies
- Maintains state with HTTP cookies using the
response and request objects - Create a cookie named gc that contains the users
name, e-mail address, and SessionID - Read the value of the cookie, and write the value
to the Web page - In the SignIn_ServerClick event procedure,
retrieve the form values and SessionID
37Creating HTTP Cookies in ASP.NET
38Maintaining State Without HTTP Cookies
- HTTP cookies were used to link the clients
session to the Session object using the SessionID - The Session timeout property specifies when the
session ends if no activity occurs - The default value for the session timeout is 20
minutes - The process of creating a cookieless application
is known as cookie munging - The cookieless property in the sessionState node
in the web.config file is used to determine if
the session key should require cookies - The Web Server appends any requested URL with the
Session ID
39Storing Session Data
- In the machine.config and the web.config files,
the sessionState node allows you to configure the
session management - Storing session data in the Web Server memory
results in the best performance - The mode property is used to identify which
storage method to use to store session data - Off - turns off session management
- InProc - the data is stored in process with the
Web Server - StateServer - stores the data with a Windows
service called StateServer
40Storing Session Data
- aspnet_state service is the StateServer service.
You can start the StateServer using the DOS
commands or the Windows Services applet - stateConnectionString identifies the TCP/IP
connection to the StateServerStart the
StateServer using the DOS Command
41Overview of ASP.NET Security Methods
- Authentication is the process of validating the
identity of the request - Authentication mode property can be set to
Windows, Passport Forms, or None. If the mode is
set to None you can setup your own custom
authentication - Define the authentication method used with the
Internet Service Manager - Anonymous - default anonymous user
IUSR_MachineName - Basic authentication, the username and password
are sent as clear text over the Internet, unless
you encrypt the login with SSL encryption - With Windows authentication, the username and
password are not sent over the Internet
42Overview of ASP.NET Security Methods
- Passport is a single sign-on passport identity
system created by Microsoft - Passport service authenticates the user, sends a
cookie back - The benefit to the user is that they only have to
login once to access multiple resources and
services - Passport at http//www.passport.com/
- The redirectURL property is the URL to redirect
the user to when the request is not authenticated
such as login page
43Authorization Node Configuration
- Authorization is the process of ensuring that you
only have access to resources that are granted by
the system administrators - Windows NTFS file system - allows you to set
permissions on individual files and folders using
an access control list (ACL) - The Identity node is used to identify which
resources can be accessed after the user is
authenticated - The Impersonate property is used to indicate if
impersonation is allowed
44Authorization Node Configuration
- identity node - used to impersonate a Windows
user account - impersonate property is used to indicate if
impersonation is allowed - allow node - is used to configure users that are
allowed to access the application - deny node - is used to configure users that are
not allowed to access the application - users property - is used to identify the user
- roles property - is used to identify a group of
users - wildcard - used to identify all users
- wildcard ? - used to identify the anonymous user
45Forms-based Authentication
- Forms Authentication is a cookie-based
authentication method - When you log in using an ASP.NET form, the Web
Server checks the IP address and domain in the
host header of the request - The user may be validated using the credential
list within the configuration files, or the
request may be validated against an XML file, a
database, an in-memory structure, an LDAP
directory, or even a Web service
46Forms-based Authentication
- ASP.NET determines if an authentication cookie is
present in the TCP/IP header packet - If there is no cookie, the client is redirected
to the login page - Once the user has been authenticated, a cookie is
added to the header packet to identify future
requests - There is no username or password stored in the
HTTP cookie. The HTTP cookie merely identifies
the client - The first time the user sends a username and
password, the cookie has not been created - Therefore, you must use SSL to encrypt the login
information until the HTTP cookie is generated
47Forms Node Configuration
- When the authentication mode is set to Forms, the
child node forms configure the HTTP cookie - Name property - identify the cookie that contains
the ID of the user, default name is .ASPXAUTH. - Path property - is the server path that is valid
for the cookie. The default path property is /
to access the cookie from any directory. - Timeout - is the valid duration of the cookie.
The default timeout value is 30 minutes. - loginUrl - is the page to redirect the user if
they have not been authenticated. The default is
login.aspx. - Protection - to protect the data in the HTTP
cookie. Possible values are All, None,
Encryption, or Validation.
48MachineKey Node Configuration
- The machineKey node is used to identify a value
and method to encrypt data on the server - The validationKey is used as part of the hash
algorithm, so only ASP.NET applications that have
the validationKey can use the data - The decryptionKey is used to guarantee that
nontrusted sources cant read the text
49Credentials Node Configuration
- The credentials node is an optional child node of
the Forms node to provide the credentials for
users that may access the application resources - passwordformat property - to specify the
encryption method used to encrypt the
credentials. The possible values are Clear, SHA1,
and MD5. SHA1 and MD5 store the password as a
hash value - user node is a child node of the credentials node
to identify users - name property identifies the username
- password identifies the users password
50Credentials Node Configuration
- Once the user is validated, you can access that
users identity information - The following sample code displays the users
name and the authentication method used in the
Web page - If User.identity.IsAuthenticated then
- Message.Text "Welcome Member " _
- user.identity.name _
- ". You were authenticated using " _
- User.identity.AuthenticationType "."
- Else
- Message.Text "Welcome Stranger!"
- End if
51Validating User Credentials
- A Users Credentials File is an XML file to store
user information such as e-mail and password - The general process is to retrieve the user login
information, retrieve the XML data, and locate
the user within the XML file - Then, if the user appears, validate the user
- If the user is not validated, they are redirected
by the Web configuration file to the login page - In the following exercises, you will import
login.aspx, home.aspx and XMLUsers.xml. Then, you
will change the configuration files to reflect
the new user authentication model
52Use XML Based Validation
- Create a new WebForm named default.aspx
- In the Page_Load procedure enter
- Import the login.aspx, home.aspx, and
XMLUsers.xml - In XMLUsers.xml add your username and password to
the list of users
53Use XML Based Validation
54Configure Forms Authentication
- In the Web.config file change the Authentication
mode from Windows to Forms - In the login.aspx page import the namespaces
- In the SignIn_ServerClick event procedure,
retrieve the values and assigns it to a variable - Create a DataSet object named ds
- Create a FileStream object named fs
- Pass the URL of the XML file named XMLUsers.xml
- Open a read-only connection to the file
55Modify the Login Page
- Create a StreamReader object named reader which
will be used to read the file - Dim reader As StreamReader New StreamReader(fs)
- Use the ReadXML method to insert the data into
the DataSet - ds.ReadXml(reader)
- Close the connection to the file using the close
command of the FileStream object - fs.Close()
- Within the DataSet, create a new table named
users - Create a new row named matches
56Setup the Home Page
- Open home.aspx and edit the DoLogOut_ServerClick
event procedure for the Log Off button - If the user is already authenticated, display a
custom message. - Otherwise, provide a hyperlink to the login page
- Add the code to the first line to import the
security namespace - Imports System.Web.Security