www.cisdocs.com

Download Report

Transcript www.cisdocs.com

JavaScript, Fifth Edition
Chapter 9
Managing State and Information
Security
Objectives
In this chapter, you will:
• Learn about state information
• Save state information with hidden form fields, query
strings, and cookies
• Learn about security issues
JavaScript, Fifth Edition
2
Understanding State Information
• State information
– Information about individual visits to a Web site
• HTTP original design: stateless
– No persistent data about site visits stored
– Information does not carry from page to page
JavaScript, Fifth Edition
3
Understanding State Information
(cont’d.)
• Reasons for maintaining state information
–
–
–
–
–
–
Temporarily store information for a user
Allow a user to create bookmarks
Provide shopping carts
Customize individual Web pages
Store user IDs and passwords
Use counters
JavaScript, Fifth Edition
4
Understanding State Information
• Methods to pass data
–
–
–
–
Cookies
Hidden form fields
Querystrings
Session variables
• Server-side
• HTML 5
JavaScript, Fifth Edition
5
HIDDEN FORM FIELDS
JavaScript, Fifth Edition
6
Saving State Information with Hidden
Form Fields
• Hidden form field
–
–
–
–
Special type of form element
Not displayed by Web browser
Allows information to be hidden from users
Created with the <input> element
– Temporarily stores data sent to a server along with
the rest of a form
– No need for user to see hidden data
JavaScript, Fifth Edition
7
Saving State Information with Hidden
Form Fields
• Syntax
– <input type="hidden“ name=“someName”>
– Name and type attributes are the only attributes
you can include with it
<script>
document.forms.someName.value = “hidden data”;
JavaScript, Fifth Edition
8
Saving State Information with Hidden
Form Fields
• Retrieving data in hidden field
– If sent using “get” method, use Location object to
parse query string
– If sent using “post” method, server side scripting
language is needed
JavaScript, Fifth Edition
9
QUERY STRINGS
JavaScript, Fifth Edition
10
Saving State Information with Query
Strings
• Query string
– Set of name=value pairs
• Appended to a target URL
– Consists of a single text string
• Contains one or more pieces of information
• Passes information from one Web page to another
JavaScript, Fifth Edition
11
Saving State Information with Query
Strings (cont’d.)
• Passing data with a query string
– Add a question mark (?) immediately after a URL
• Followed by the query string (in name=value pairs) for
the information to preserve
– Ampersands (&)
• Separates individual name=value pairs within the query
string
– Example:
<a href="http://www.URL.com/TargetPage.html?
firstName=Don&lastName=Gosselin&occupation=writer">
Link Text</a>
JavaScript, Fifth Edition
12
Saving State Information with Query
Strings (cont’d.)
• When the QueryString is received by the next web
page, it must be
– 1) obtained using the Location object
– 2) split up into individual pieces of data, via parsing
• Extracting characters of parts of a string of text
(substrings)
– String object contains methods for manipulating strings
JavaScript, Fifth Edition
13
Saving State Information with Query
Strings (cont’d.)
• Passed query string assigned to target Web page
Location object search property
• search property of the Location object contains a
URL’s query or search parameters
• From preceding example:
<a href="http://www.URL.com/TargetPage.html?
firstName=Don&lastName=Gosselin&occupation=writer">
Link Text</a>
– location.search will return
"?firstName=Don&lastName=Gosselin&occupation=writer”
– syntax:
var x = location.search();
JavaScript, Fifth Edition
14
Saving State Information with Query
Strings (cont’d.)
• X is now equal to
"?firstName=Don&lastName=Gosselin&occupation=writer”
• Remove the question mark
– Using the substring() method combined with the length
property
– Example:
// Assigns the query string to the x variable
var x = location.search;
// Removes the opening question mark from the string
queryData = x.substring(1,x.length)
// queryData is now equal to
firstName=Don&lastName=Gosselin&occupation=writer”
JavaScript, Fifth Edition
15
Saving State Information with Query
Strings (cont’d.)
• Next, convert individual pieces of information into array
elements using the split() method
– // queryData is now equal to
firstName=Don&lastName=Gosselin&occupation=writer”
• Convert the information in the queryData variable into an
array named queryArray[]
// splits queryData into an array
var queryArray = queryData.split("&");
QueryArray now has this data:
QueryArray[0] is equal to firstName=Don
QueryArray[1] is equal to lastName=Gosselin
QueryArray[2] is equal to occupation=writer
JavaScript, Fifth Edition
16
Saving State Information with Query
Strings (cont’d.)
QueryArray now has this data:
QueryArray[0] is equal to firstName=Don
QueryArray[1] is equal to lastName=Gosselin
QueryArray[2] is equal to occupation=writer
Next, EXTRACT DATA
queryFields = QueryArray[0].split(“=“);
queryFields[0] will be equal to firstName
queryfields[1] will be equal to Don
JavaScript, Fifth Edition
17
COOKIES
JavaScript, Fifth Edition
18
Saving State Information with Cookies
• Query strings and hidden form fields temporarily
maintain state information
• Cookies
– Small pieces of information about a user
– Stored by a Web server in text files
– Stored on the user’s computer
• When Web client visits a Web server
– Saved cookies sent from client to the server
JavaScript, Fifth Edition
19
Saving State Information with Cookies
• Cookies can be temporary or persistant
– Temporary cookies
• Available only for current browser session
– Persistant cookies remain available beyond the
current browser session
JavaScript, Fifth Edition
20
Introducing Cookies
• Cookie is variable that is used to store data and
pass that data from page to page
– Client side cookies
• variable is stored on visitors PC
• browsers place limits on size and number of client-side
cookies
• contain textual data only
• cannot contain a computer virus
– Server side cookies
• Variable is stored on web server
Client side vs Server side
• Client-side
– JavaScript code is executed on client to create cookie
– Cookie is stored in a browser specific folder on PC
– When a web page requests another web page, cookie
is sent to that page on web server
• Server-side
– script code is executed on server to create cookie
– Cookie is stored in a specific folder on webserver, tied
to requestor
– Cookie is not transmitted but can be used prior to a
web pages delivery to PC
Cookies and Web Browsers
• Browser considerations
– Each browser handles and stores cookies in a
different way
– A cookie generated while viewing a Web site under
one browser is not available if user switches to a
different browser
• Most often cookies are used to identify a user, or
what a user is doing
Cookies and Web Browsers
Internet Explorer
Firefox
Saving State Information with Cookies
(cont’d.)
• Persistent cookies
– Remain available beyond current browser session
• Stored in a text file on a client computer
• Limitations on the use of cookies
– Server or domain can store a maximum of 20 cookies
– Total cookies per browser cannot exceed 300
– Largest cookie size is 4 kilobytes
JavaScript, Fifth Edition
25
WRITING A COOKIE
JavaScript, Fifth Edition
26
Creating and Modifying Cookies
• Use the cookie property of the Document object
– Creates cookies in name=value pairs
– Syntax
• document.cookie = name + "=" + value;
• Cookie property created with a required name
attribute and four optional attributes:
– expires, path, domain, secure
JavaScript, Fifth Edition
27
Structure of a Cookie
• Cookie MUST have a name
• May have other data, such as
–
–
–
–
How long it persists
Where it lives
Which domain it is associated with
If it’s secure
• Cookie structure is in parameter name & value pairs
– name=value;expires=date;path=directory; domain=domain-name;secure
– Only the name=value pair is required
Writing a cookie
• Name is the only required attribute
• Syntax:
document.cookie = “ name = value”;
document.cookie = “myCartoonCharacter” = cname;
document.cookie = “myCartoonCharacter=Barney”;
Creating and Modifying Cookies
(cont’d.)
• name attribute
– Only required parameter
– Specifies cookie’s name=value pair
– Cookies created with only the name attribute:
• Temporary cookies
– cookie property adds another entry to a list of
cookies
– Example: build a list of cookies
• document.cookie = "firstName=" + "Don";
• document.cookie = "lastName=" + "Gosselin";
• document.cookie = "occupation=" + "writer";
JavaScript, Fifth Edition
30
Creating and Modifying Cookies
(cont’d.)
• Cookies cannot include semicolons or special characters
– Can use special characters in cookies if using encoding
• Use escape functions to convert non-alphanumeric
characters into escape codes
– escape()
– encodeURI()
– encodeURIComponent()
• Use unescape functions to convert escape codes into
non-alphanumeric characters
– unescape()
– unencodeURI()
– unencodeURIComponent()
JavaScript, Fifth Edition
31
Escape Character Codes
and Functions
Escape Character Codes
and Functions (continued)
Creating a cookie
document.cookie = “myCartoonCharacter=escape(‘Barney Rubble’)”;
Or
var myCookieName = “myCartoonCharacter”;
var myCookieValue=“Braney Rubble”;
document.cookie = myCookieName + “=“ + escape(myCookieValue);
Blank will convert to %20, so
myCookieValue will equal Barney%20Rubble
Creating and Modifying Cookies
(cont’d.)
– For older browsers
• Manually encode and decode cookies
– Example exercise:
• Modify Customer Information and Product Information
forms so that fields saved in temporary cookies instead
of in query strings
JavaScript, Fifth Edition
35
PERSISTING COOKIES
JavaScript, Fifth Edition
36
Creating and Modifying Cookies
(cont’d.)
• expires attribute
– Determines how long a cookie can remain on a client
system before being deleted
– Cookies created without this attribute
• Available current browser session only
– Syntax: expires=date
• name=value pair and the expires=date pair
separated by a semicolon
– Do not encode expires attribute
JavaScript, Fifth Edition
37
Setting the Cookie
Expiration Date
• Server-side
– Session cookies expire when current Web session is
completed
– Do not need expiration date
• Client-side
– Persistent cookies exist until a specified expiration
date
expires=weekday, dd-mmm-yyyy hh:mm:ss GMT
Setting the Cookie
Expiration Date
• Setting expiration dates
– Use a date object
– Convert into proper format using .toGMTString()
method
document.cookie = “myCartoonCharacter=escape(‘Barney Rubble’);
expires=Tue, 23-Apr-2013 00:00:01“;
var dateObj = new Date();
document.cookie = “myCartoonCharacter=escape(‘Barney Rubble’);
expires=‘”+ dateObj.toGMTString();
COOKIE AVAILABILITY
JavaScript, Fifth Edition
40
Setting the Cookie Path
• Cookies are associated with folders and directories,
not a single document
• Cookies created in one Web page can be
accessible to other pages in the Web site
Setting the Cookie Path
• To ensure that a cookie is readable from within any
folder on the Web server, set the path to the root
folder of the Web server
– No need to set the cookie path if all Web pages are
placed within a single folder on the server; cookie
path is a concern only if pages are stored in different
directories
document.cookie = "myName=‘joe'; path='/folder1'";
document.cookie = "myName=‘joe'; path='/'";
COOKIE DOMAIN
JavaScript, Fifth Edition
43
Setting the Cookie Domain
• Cookies are restricted to work within a particular
Web domain and cannot be accessed across
domains
• For a site that employs multiple domains and
subdomains, add the text string ;domain=domainname
– The cookie will be available to any page within the
domain or its subdomains
– acad-stuweb1.elcamino.edu
document.cookie = "myName=‘joe'; domain=‘www.elcamino.edu’”
Setting Cookie Security
• Define whether or not the cookie can be sent only to
a Secure Sockets Layer (SSL) using the HTTPS
transfer protocol
• To force the browser to employ a secure channel:
– Add the text string ;secure to the cookie definition
• If the secure keyword is omitted from the cookie
definition, the browser will transfer the cookie using
the HTTP protocol
document.cookie = "myName=‘joe'; secure”
Setting Cookie Security
• secure attribute
– Indicates cookie can only be transmitted across a
secure Internet connection
• Using HTTPS or another security protocol
– Example:
document.cookie = "firstName=Don"+ ";secure=true");
JavaScript, Fifth Edition
46
READING A COOKIE
JavaScript, Fifth Edition
47
Reading a Cookie
• Just refer to the object’s property
var x = document.cookie
Reading Cookies with JavaScript
• Parsing a cookie
– Decode it using decodeURIComponent() function
– Use the String object methods to extract individual
name=value pairs
– Similar to parsing query strings
• Do not need to remove the question mark at the
beginning of the string
• Individual cookies separated by a semicolon and a
space instead of ampersands
JavaScript, Fifth Edition
49
Reading Cookies with JavaScript
(cont’d.)
document.cookie = "city=Boston";
document.cookie = "team=Red Sox";
document.cookie = "sport=baseball";
var cookieString = document.cookie;
var cookieArray = cookieString.split("; ");
var yourTeam;
for (var count = 0; count < 3; ++count)
{
yourTeam = cookieArray[count];
if (yourTeam.substring(0,yourTeam.indexOf("="))== "team")
{
document.write("Your team is the "
+ yourTeam.substring(yourTeam.indexOf("=")+ 1,yourTeam.length));
}
}
JavaScript, Fifth Edition
50
DELETING A COOKIE
JavaScript, Fifth Edition
51
Deleting a Cookie
• Set the cookie’s expiration date to a past date
document.cookie = "myinfo=‘Joe'; expires=Tue, 23-Apr-2010 00:00:01";
• Manually delete cookies within Options or
Preferences dialog box of most browsers
MULTI-VALUE COOKIES
JavaScript, Fifth Edition
53
Storing Multiple Values
in a Cookie
• Commonly used with forms
• Uses subkeys to the “name/value” key
– Confusing use of the “=“ sign
– To store multiple values in a cookie, format the
name/value pair as
cookieName=field1=value1&field2=value2&field3=value3
Reading a Multi-Value Cookie
• First retrieve the entire cookie value
• Then retrieve the value of a specific subkey within
that value
• Use the split() method to split a cookie into an array:
– var cookiesArray = document.cookie.split("; ");
– May need to do this several times for multi-value
cookies to separate out the “&” symbol between
name/value pairs
COOKIE SUPPORT
JavaScript, Fifth Edition
57
Testing for Cookie Support
• To test whether cookies are enabled by a current
Web browser:
– Use navigator.cookieEnabled object property
– Ex.
If (navigator.cookieEnabled)
{
//statements
}
COOKIE SECURITY
JavaScript, Fifth Edition
59
Understanding Security Issues
• Security threats
– Viruses, worms, data theft by hackers
– Consider Web server security and secure coding
issues
– Web server security technologies
• Firewalls
• Secure Socket Layer (SSL)
JavaScript, Fifth Edition
60
Secure Coding with JavaScript
• Secure coding or defensive coding
– Writing code to minimize any intentional or accidental
security issues
• All code: insecure unless proven otherwise
• No magic formula for writing secure code
JavaScript, Fifth Edition
61
JavaScript Security Concerns
• Security areas of most concern
– Protection of a Web page and JavaScript program
against malicious tampering
– Privacy of individual client information
– Protection of the local file system of the client or Web
site from theft or tampering
• Another security concern
– Privacy of individual client information in the Web
browser window
• Important JavaScript security feature
– Lack of certain types of functionality
JavaScript, Fifth Edition
62
SAME ORIGIN POLICY
JavaScript, Fifth Edition
63
The Same Origin Policy
• Restricts how JavaScript code in one window or
frame accesses a Web page
– In another window or frame on a client computer
• domain property of the Document object
– Changes origin of a document to its root domain
name
– Allows documents from different origins in the same
domain to access each other’s elements and
properties
JavaScript, Fifth Edition
64
The Same Origin Policy
• To view and modify elements in other windows and
frames
– They must have the same protocol and exist on the
same Web server
• Same origin policy applies to:
– The domain name
– The server on which a document located
JavaScript, Fifth Edition
65
The Same Origin Policy (cont’d.)
• Policy prevents:
– Malicious scripts from modifying content of other
windows and frames
– Theft of private browser information and information
displayed on secure Web pages
• Policy protects integrity of Web page design
JavaScript, Fifth Edition
66
The Same Origin Policy (cont’d.)
Figure 9-7 Firefox error message demonstrating the same
origin policy
Figure 9-8 Internet Explorer error message
demonstrating the same origin policy
JavaScript, Fifth Edition
67