Chapter Objectives
description
Transcript of Chapter Objectives
Introduction to ASP.NET, Second Edition 2
Chapter Objectives
Introduction to ASP.NET, Second Edition 3
Web Applications (Page 464)
• Web application – Group of files and folders (including virtual folders)
located in Web applications root directory
– Virtual Web and directories
– Stored outside of the C:\Inetpub\wwwroot\ folder
• Internet Information Services Management Tools– Create Chapter9 project and import files
– Microsoft Management Console (MMC)• %systemroot%\System32\inetserv\iis.mmc
Introduction to ASP.NET, Second Edition 4
The Internet Information Services Management Tools
Introduction to ASP.NET, Second Edition 5
The Internet Information Services Management Tools (continued)
Introduction to ASP.NET, Second Edition 6
Web Application Memory Models
Introduction to ASP.NET, Second Edition 7
Web Application Memory Models (continued)
• Create Chapter9High process• Configure to run in isolated process – IIS MMC – Directory tab, change Application
Protection property to High(Isolated)
• Use Component Services– %systemroot%\system32\Com\comexp.msc
Introduction to ASP.NET, Second Edition 8
Web Application Memory Models(continued, Page 468)
Introduction to ASP.NET, Second Edition 9
Web Application Memory Models (continued)
Introduction to ASP.NET, Second Edition 10
Session Data
• User information tracked across user sessions – HTTP headers - ServerVariables collection
– SessionID - identifies each session
– Read Session ID, ServerVariables, store data
Dim SID As String = Session.SessionID
Session("UserAgent") = Request.UserAgent.ToString
Session("SID") = SID
Dim strName As String = txtName.Text
Session("username") = strName
Introduction to ASP.NET, Second Edition 11
SessionGetVariables.aspx (Page 471)
Introduction to ASP.NET, Second Edition 12
Session Data (continued)
Introduction to ASP.NET, Second Edition 13
Building Information Management Security Policies
• Security Policies– Sample – encode forms to prevent entering <>
Dim strName As String
strName = txtName.ToString
message.Text = "Welcome " &
HTTPUtility.Encode(strName)
• Privacy Policies– Inform user about information being collected and what is
being done with that information
Introduction to ASP.NET, Second Edition 14
Application Configuration
• Registry - Windows applications store configuration settings
• Metabase stored Web application configuration• To access the Metabase – Microsoft Management Console (MMC) – local
application
– Windows Scripting Host (WSH) - creates scripts to access the Metabase
– ASP.NET configuration files
Introduction to ASP.NET, Second Edition 15
Viewing the Web Server Property Pages(Page 477)
• Web Site Tab – IP address and Port
– HTTP Keep-Alives Enabled - maintain state
– W3C Extended Log File Format • Extended properties
• Default location - %WinDir%\System32\LogFiles
• Default directory - is W3SVC1
• Log filename - is named after the date
• Local time
Introduction to ASP.NET, Second Edition 16
Viewing the Web Server Property Pages (continued)
Introduction to ASP.NET, Second Edition 17
Viewing the Web Server Property Pages (continued)
Introduction to ASP.NET, Second Edition 18
Viewing the Web Server Property Pages (continued)
Introduction to ASP.NET, Second Edition 19
Viewing the Web Server Property Pages (continued)
• Documents tab– Default document name– Document Footer
• HTTP Headers tab– Expire page content– Internet Content Rating Association (ICRA)
• Home Directory tab– Web site location – Properties – Read, Write, Directory browsing, Log visits
property, Index this resource, Script source, Execute, Scripts only
– Configuration
Introduction to ASP.NET, Second Edition 20
Viewing the Web Server Property Pages (continued)
Introduction to ASP.NET, Second Edition 21
Viewing the Web Server Property Pages (continued)
Introduction to ASP.NET, Second Edition 22
Application Configuration Files
• XML-based – Machine-level - machine.config
– Application - Web.config
• settings configured as a node, include nested child nodes– Root node - <configuration>
– ConfigSections node - identify configuration sections • system.web - Web configuration settings
Introduction to ASP.NET, Second Edition 23
The AppSettings Configuration Node
• Key/value pairs - application variables
<appSettings><add key="SN" value="Tara Store" />
</appSettings>
• Retrieve
dim SN as string
SN = ConfigurationSetttings.AppSettings("SN")
Introduction to ASP.NET, Second Edition 24
The Pages Configuration Node
• How content is delivered to the Web page– Buffer - area in memory on the server
– enableSessionState - use Session
– enableViewState - store data in ViewState
– enableViewStateMac - validate data in ViewState
– autoEventWireup - override Page_OnLoad event
– SmartNavigation - continue at the row where they left off when they refresh the page
Introduction to ASP.NET, Second Edition 25
The httpRuntime Configuration Node
• Properties:– executionTimeout - time allowed to execute before the
request times out
– maxRequestLength - kilobytes accepted from an HTTP request
– UseFullyQualifiedRedirectURL - fully qualify the URL when the client has been redirected to a new page
Introduction to ASP.NET, Second Edition 26
Globalization Configuration Node
• Encoding standard– Unicode - each character set has its own identity
• Default value is UTF-8
• All Unicode character values are supported
• Culture and uiCulture – Can set at page level, to configure language & dates
– Identify a language and culture string• fr-FR for French
• en-US for United States English
Introduction to ASP.NET, Second Edition 27
Setting the Culture Property France.aspx (Page 489)
Introduction to ASP.NET, Second Edition 28
Compilation Node Configuration
• Language compilers build applications– DefaultLanguage property
• Can set at page level <%@ Page Language="vb" %>
– Explicit - declare your variables
– Strict - declare the variable data type
<compilation debug="false"
explicit="true" defaultLanguage="vb" >
</compilation>
Introduction to ASP.NET, Second Edition 29
Trace Node Configuration
• Properties– enabled - turn tracing on
– localOnly - results displayed at http://localhost/.
– traceMode - sort trace results
– pageOutput - display results with Web page
– trace stack – stores data
– requestLimit - number of trace results stored
Introduction to ASP.NET, Second Edition 30
Trace Node Configuration (continued)
• Trace.Write – Trace.Write – writes data to trace stack
– Trace.Warn shows up in red font
– Trace.Write("CategoryName", "Value")
• TraceTool– http://localhost/approot/Trace.axd
– http://localhost/Configuration/Tracing/TraceTool/trace.axd
Introduction to ASP.NET, Second Edition 31
Trace Node Configuration (continued)
Introduction to ASP.NET, Second Edition 32
Using the Trace Utility Program Trace.aspx (Page 493)
• Change Web.config
<trace enabled="true"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
/>
Introduction to ASP.NET, Second Edition 33
Trace.aspx (continued)
Introduction to ASP.NET, Second Edition 34
Trace.aspx (continued)
Introduction to ASP.NET, Second Edition 35
Trace.aspx (continued)
Introduction to ASP.NET, Second Edition 36
CustomErrors Node Configuration
• Both ASP.NET and IIS provide error pages – IIS Web pages - c:\winnt\Help\iisHelp\common\
directory• MMC - configure custom error pages
– HTTP status message code - status of request• 200 - success
• 404 - file requested could not be found
• 400’s usually indicate a client-related error
• 500’s usually indicate a server-related error
Introduction to ASP.NET, Second Edition 37
CustomErrors Node Configuration (continued)
• Properties: – Mode – where to display rich error pages (yellow)
• RemoteOnly - only locally
• On - custom error pages except at localhost
• Off - ASP.NET error pages displayed
– defaultRedirect property - sets a default error page if no custom error page is configured
– error node – uses statusCode to redirect user
Introduction to ASP.NET, Second Edition 38
CustomErrors Node Configuration (continued)
<customErrors
mode="RemoteOnly"
defaultRedirect="/defaultError.aspx"/>
<error
statusCode="404"
redirect="/error404.aspx"/>
</customErrors>
Introduction to ASP.NET, Second Edition 39
CustomErrors Node Configuration (continued)
Introduction to ASP.NET, Second Edition 40
Maintaining State in an ASP.NET Application
• Methods - unique identifier to recognize the client across Web pages: – ViewState – with hidden fields
– Client-Side Cookies -
– ASP.NET uses Application and Session objects
– Cookieless applications – identification data is passed with the URL.
Introduction to ASP.NET, Second Edition 41
Client-Side Cookies
• Small piece of information stored on client– Cookies collection - group of cookies
• Sent by the server through the header
• Browser writes the cookie
<script language="JavaScript">
document.cookie = "CookieEmail=kkalatatarastore.com;
expires =Monday, 07-Jan-07 12:00:00 GMT";
readCookie = document.cookie;
</script>
Introduction to ASP.NET, Second Edition 42
Client-Side Cookies (continued)
Introduction to ASP.NET, Second Edition 43
Client-Side Cookies ClientCookies.aspx (Page 499)
Introduction to ASP.NET, Second Edition 44
Cookie Settings in the Internet Explorer Browser
Introduction to ASP.NET, Second Edition 45
Cookie Settings in the Internet Explorer Browser (continued)
Introduction to ASP.NET, Second Edition 46
Cookie Settings in the Internet Explorer Browser (continued)
Introduction to ASP.NET, Second Edition 47
Creating Cookies with ASP.NET
• HTTP cookies - created by the Web server – SessionID - value of the HTTP cookie
• Retrieve using server variable HTTP_COOKIE
<% Request.ServerVariables("HTTP_COOKIE") %>
• Response.Cookies – Sends cookie to browser in Set-Cookie header
– Named group of cookies - dictionary cookie
– Individual cookies - cookie keys
Introduction to ASP.NET, Second Edition 48
Creating Cookies with ASP.NET (continued)
• Create cookie
<% Response.Cookies("myCookie") = "value" %>
<% Response.Cookies("myCookie").Expires = "MM DD, YYYY" %>
• Read cookie
<% Request.Cookies("myCookie")%>
Introduction to ASP.NET, Second Edition 49
Maintaining State with Cookies Cookies.aspx (Page 505)
Introduction to ASP.NET, Second Edition 50
Cookies.aspx (continued)
Introduction to ASP.NET, Second Edition 51
Maintaining State Without HTTP Cookies
• HTTP cookies used to link session to Session object using SessionID– Session timeout - session ends if no activity – Default - 20 minutes
• Cookie Munging or (Cookieless appication)– cookieless = true in sessionState node – Web server appends any requested URL with Session
ID (it appears like a subdirectory)– SessionID doesn’t contain the session data. The
session data is still maintained by the Web server or outside the web server.
Introduction to ASP.NET, Second Edition 52
Creating a Cookieless Web Application Cookieless.aspx (Page 508)
• Change Web.config
<sessionState cookieless=“true" timeout="2"
/>
• View page – it’s set to 2 minutes to make it faster to
view changes.
Introduction to ASP.NET, Second Edition 53
Cookieless.aspx (continued)
Introduction to ASP.NET, Second Edition 54
Storing Session Data
• sessionState node for configuring session management
– Mode property - session storage method
• Off - turns off
• InProc - in process with Web Server
• StateServer - StateServer Windows service
• SQLServer – SQL Server (includes MSDE)
Introduction to ASP.NET, Second Edition 55
Using the Web Server to Manage Session Data
• All session data lost if stop and start Web server
<sessionState mode="InProc"
cookieless="true"
timeout="20"
/>
Introduction to ASP.NET, Second Edition 56
Using State Server to Manage Session State (Page 511)
• aspnet_state service – Start - DOS or Windows Services– stateConnectionString - connection to StateServer
• Need to accept HTTP session cookies
• Change Web.config
<sessionState mode="StateServer"stateConnectionString="tcpip=127.0.0.1:42424"stateNetworkTimeout="10"cookieless="false" timeout="20" />
Introduction to ASP.NET, Second Edition 57
Using State Server to Manage Session State (continued)
Introduction to ASP.NET, Second Edition 58
Using SQL Server to Manage Session State InstallSqlState.sql (Page 515)
• Configure SQL Server
CD C:\WINNT\Microsoft.net\Framework\[Version]\
OSQL – S localhost –U sa –P password <InstallSqlState.sql
• Change Web.config
<sessionState mode="SQLServer"sqlConnectionString= "data source=MACHINENAME\NetSDK; user id=sa;password=password"cookieless="false" timeout="20"
/>
Introduction to ASP.NET, Second Edition 59
Using SQL Server to Manage Session State (continued)
Introduction to ASP.NET, Second Edition 60
Using SQL Server to Manage Session State SessionSetVariables.aspx
(Page 516)
Introduction to ASP.NET, Second Edition 61
ASP.NET Security Methods
• Authentication - validating identity of request– Windows, Passport Forms, or None.
• Identity Node– Impersonate user account
<identity impersonate="false" userName="" password=""/>
Introduction to ASP.NET, Second Edition 62
MachineKey Node Configuration
• Identify value and method to encrypt data – validationKey - Only valid applications use data
– decryptionKey – Nontrusted can’t read data
– Autogenerate the key values (not Web Farm) • validation – encryption method
<machineKey
validationKey="AutoGenerate"
decryptionKey="AutoGenerate"
validation="SHA1"
/>
Introduction to ASP.NET, Second Edition 63
Authenticating Users
• Custom Authentication– Mode – None
• Passport – Single sign-on identity system
– Passport service authenticates user, send cookie
– redirectURL – when user is not authenticated
<authentication mode="passport">
<passport redirectURL="gohere"/>
</authentication>
Introduction to ASP.NET, Second Edition 64
Authenticating Users with Windows Authentication
• NTFS file and folder security - Windows Explorer
– Full Control – can change permission settings
– Modify – view and modify file properties, add and delete files
– No Access – no access to the resource
• Web site security properties with MMC
• Web application settings in configuration files
Introduction to ASP.NET, Second Edition 65
Web Server Permissions
• Anonymous access
– IUSR_MachineName - Internet Guest Account -
• Authenticated access
– Basic authentication
• username and password sent as clear text unless encrypt with SSL
– Windows authentication
• username and password are not sent
Introduction to ASP.NET, Second Edition 66
Web Server Permissions (continued)
Introduction to ASP.NET, Second Edition 67
Web Server Configuration FilesWindowsAuthentication.aspx (Page 523)
• Default –Windows
<authentication mode="Windows" />
<identity impersonate="true" />
• Only allow administrator users
<authorization>
<allow roles="BUILTIN\Administrators"
users="BUILTIN\Administrator" />
<deny users="*" />
</authorization>
Introduction to ASP.NET, Second Edition 68
WindowsAuthentication.aspx (continued)
Introduction to ASP.NET, Second Edition 69
Authorization Node Configuration
• Access to resources – NTFS - set permissions with access control list
– Authorization node• Allow and deny nodes
• Users - identify the user
• Roles - identify a group of users
• Wildcards – * all users
– ? the anonymous user
Introduction to ASP.NET, Second Edition 70
Authorization Node Configuration (continued)
• Resource-based– Individual resources assigned permissions
– Only in small sites
• Role-based– Users assigned to groups
– Groups assigned permissions to resources
– Scalable
– Recommended strategy • Front-end authentication - assign users to roles
Introduction to ASP.NET, Second Edition 71
Authenticating Users with Forms Authentication
• Cookie-based – Authentication cookie in header packet
• No username or password stored
• Identifies the client
• Use SSL to encrypt the login
– No cookie, redirected to the login page
– User validated using the credential list within • Configuration files, XML file, Database
• In-memory structure, LDAP directory, Web Service
Introduction to ASP.NET, Second Edition 72
Forms Node Configuration
• Properties– Name - identify the cookie that contains the ID of the
user, default name is .ASPXAUTH.
– Path - is the server path valid for the cookie• default path property is “/” to access the cookie from
any directory
– Timeout - valid duration - default is 30
– loginUrl - redirect page - default is “login.aspx”
– Protection - protect HTTP cookie• All, None, Encryption, or Validation
Introduction to ASP.NET, Second Edition 73
Credentials Node Configuration
• Provide the credentials for users – passwordformat property - encryption method
• Clear, SHA1, and MD5 - store password as a hash value
– user node - identify users• name - username
• password – password
• Creating a Hash Value – encrypt values
Introduction to ASP.NET, Second Edition 74
Credentials Node Configuration (continued)
<authentication>
<forms
name=".ASPXAUTH"
loginurl="login.aspx"
protection="all"
timeout="30"
path="/" ><credentials passwordFormat="SHA1">
<user name="User1" password="password1"/>
<user name="User2" password="password2"/>
</forms>
</authentication>
Introduction to ASP.NET, Second Edition 75
Credentials Node Configuration CreateHashValue.aspx (Page 529)
Introduction to ASP.NET, Second Edition 76
Storing User Credentials in an XML File
• Method 1 - "XMLUserEmail.xml"
<userlist>
<user>
<email>kkalata</email>
<password>painter</password>
</user>
</userlist>
Introduction to ASP.NET, Second Edition 77
Storing User Credentials in an XML File (continued)
• Import namespaces
• Retrieve the values
• Create a DataSet object
• Create a FileStream object to retrieve a file
• Pass URL to XML file as a parameter to a FileStream
• Use ReadXml method of DataSet to retrieve the data and populate the DataSet
• Close the FileStream
• Use DataTable object and DataRow object to search for the user
Introduction to ASP.NET, Second Edition 78
Storing User Credentials in an XML File (continued)
Introduction to ASP.NET, Second Edition 79
Forms Authentication Using Credentials SimpleFormsAuthentication.aspx (Page 532)
<authentication mode="Forms" ><forms name=".SIMPLELOGIN"
loginUrl="/Chapter9/SimpleLogin.aspx"path="/"protection="All" timeout="20">
<credentials passwordFormat="SHA1" ><user name = "kkalata" password = "32562DB2022ABCC6384939403AA882ABB9542D04" /><user name = "student" password = "5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8" />
</credentials> </forms>
</authentication>
<authorization> <deny users="?" />
</authorization>
Introduction to ASP.NET, Second Edition 80
Forms Authentication Using an XML File XMLUsers.xml (Page 533)
<student>password</student>
• Web.config
<authentication mode="Forms">
<forms name=".XMLLOGIN"
loginUrl="/Chapter9/XMLLogin.aspx"
path="/"
protection="All"
timeout="20">
</forms>
</authentication>
Introduction to ASP.NET, Second Edition 81
Forms Authentication Using an XML File XMLLogin.aspx (continued)
• Import the namespacesImports System.Web.Security Imports System.XmlImports System.IO
• Retrieve values from form and compare to XML file
Dim pwd As String = Password.ValueDim user As String = Username.ValueDim myFile As String = _ Server.MapPath("XMLUsers.xml").ToString
Dim xmlDoc As New XmlDocumentxmlDoc.Load(myFile)Dim UserNode As XmlNodeList = _xmlDoc.GetElementsByTagName(user)
Introduction to ASP.NET, Second Edition 82
Forms Authentication Using an XML File XMLLogin.aspx (continued)
If Not UserNode Is Nothing Then
If pwd = _
UserNode(0).FirstChild().Value Then
FormsAuthentication.RedirectFromLoginPage _
(user, Persist.Checked)
End If
End If
• XMLFormsAuthentication.aspx – Redirect to XMLLogin.aspx if not authenticated
Introduction to ASP.NET, Second Edition 83
Forms Authentication Using a Database WebUsers (Page 535)
• Create database WebUsers– Create Users table - UserEmail and UserPass
• Insert data with stored procedure
CREATE PROCEDURE dbo.InsertData
AS
INSERT INTO users (UserEmail, UserPass )
VALUES ('student', 'password')
. . .
RETURN
Introduction to ASP.NET, Second Edition 84
Web.config (Page 536)
• Change the Web.Config file
<authentication mode="Forms">
<forms name=".DBLOGIN"
loginUrl="/Chapter9/DBLogin.aspx"
path="/"
protection="All"
timeout="20">
</forms>
</authentication>
Introduction to ASP.NET, Second Edition 85
Forms Authentication Using a Database DBLogin.aspx (Page 536)
• Import the namespaces• Retrieve the values and compare to the database
values - build SQL statement
Dim strSQL As String
strSQL = "SELECT * FROM Users WHERE UserEmail='" _
& strUsr & "' AND UserPass='" & strPwd & "'"
Introduction to ASP.NET, Second Edition 86
Forms Authentication Using a Database DBLogin.aspx (continued)
• blnIsAuth stores if present in database• Set the Authentication to Persist • Preview the DBFormsAuthentication.aspx page
If blnIsAuth ThenFormsAuthentication.RedirectFromLoginPage _(strUsr, Persist.Checked)
ElseMessage.Text = _"We couldn't locate your login " & _ "information.<br />" & _"Please try to log in again.<br />"
End If
Introduction to ASP.NET, Second Edition 87
Summary
• Web application is a group of files and folders
• IIS Web server software configures applications
• MMC management tool
• Web application can be run within Web Server memory, or in a pooled or isolated process
• Security includes protecting resources
• It’s important to have a Security and Privacy Policy
Introduction to ASP.NET, Second Edition 88
Summary (continued)
• Web server will log data related to HTTP requests
• MMC allows you to configure permissions and application settings
• Web.config is an XML-compliant file that configures the Web application
• SessionID identifies the client
• Cookie is a text file stored on the client
• Store session data within Web Server process, State Server, or SQL Server database
Introduction to ASP.NET, Second Edition 89
Summary (continued)
• Authorization can be configured via Web.config or NTFS
• Anonymous authentication uses Internet Guest Account
• Basic authentication sends login data as clear text
• Windows authentication allows the user to log in
• Forms authentication is a cookie based technique to protect the Web application
• XML, Database, and static data sources work with Forms authentication