A1256655289hPekK - PowerPoint PPT Presentation

1 / 65
About This Presentation
Title:

A1256655289hPekK

Description:

The ability to store user information, including preferences, passwords, and ... Provide shopping carts that store order information. Store user IDs and passwords ... – PowerPoint PPT presentation

Number of Views:29
Avg rating:3.0/5.0
Slides: 66
Provided by: D2153
Category:

less

Transcript and Presenter's Notes

Title: A1256655289hPekK


1
JavaScript, Third Edition
Chapter 8
Cookies And Security
2
Objectives
  • Learn about state information
  • Save state information with hidden form fields,
    query strings, and Cookies
  • Manipulate strings
  • Learn about security issues

3
Introduction
  • The ability to store user information, including
    preferences, passwords, and other data, is very
    important
  • Improves usability of a Web page
  • The three most common tools for maintaining state
    information are
  • Hidden form fields
  • Query strings
  • Cookies

4
Understanding State Information
  • State Information
  • Information about individual visits to a Web site
  • HTTP was originally designed to be stateless
  • Web browsers stored no persistent data about a
    visit to a Web site
  • Design was efficient, but limiting

5
Understanding State Information (Cont.)
  • Server that maintains state information can
  • Customize individual Web pages based on user
    preferences
  • Temporarily store information for a user as a
    browser navigates within a multipart form
  • Allow a user to create bookmarks for returning to
    specific locations within a Web site

6
Understanding State Information (Cont.)
  • Provide shopping carts that store order
    information
  • Store user IDs and passwords
  • Use counters to keep track of how many times a
    user has visited a site

7
Saving State Information with Hidden Form Fields
  • Hidden form field
  • Not displayed by the Web browser
  • Allows you to hide information from users
  • Created with the ltinputgt element
  • Temporarily stores data that needs to be sent to
    a server along with the rest of a form, but that
    a user does not need to see

8
Saving State Information with Hidden Form Fields
(Cont.)
  • Is created using the same syntax used for other
    fields created with the ltinputgt element
  • ltinput type"hidden"gt
  • Name and value attributes are the only attributes
    that you can include with it

9
Example
  • Goal use multiple web pages for a single form.
  • Technique
  • use multiple frames and hidden fields
  • One frame contains hidden fields which will
    contain all of the data to be sent
  • The second frame will contain one page of the
    form.
  • As the user moves from form to form in the second
    frame, data is stored in the hidden fields in the
    first frame.

10
ExampleProductRegistration.html
  • The page
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtProduct Registrationlt/TITLEgt
  • lt/HEADgt
  • ltFRAMESET ROWS"60, "gt
  • ltFRAME SRC"TopFrame.html" NAME"topframe"
    SCROLLINGnogt
  • ltFRAME SRC"CustomerInfo.html"
    NAME"bottomframe"gt
  • lt/FRAMESETgt
  • lt/HTMLgt
  • The first frame will contain hidden fields that
    will hold all of the data.
  • The second frame will hold each individual form.

11
Example
  • The first form page page
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtCustomer Informationlt/TITLEgt
  • ltSCRIPT LANGUAGE"JavaScript"gt
  • lt!-- HIDE FROM INCOMPATIBLE BROWSERS
  • function confirmReset()
  • var resetForm confirm("Are you sure you want
    to reset the form?")
  • if (resetForm true)
  • return true
  • return false

12
Example
  • More of the first form page page
  • function nextForm()
  • parent.topframe.document.hiddenElements.name.value
  • document.customerInfo.name.value parent.topfram
    e.document.hiddenElements.address.value
  • document.customerInfo.address.value parent.topfra
    me.document.hiddenElements.city.value
  • document.customerInfo.city.value
  • parent.topframe.document.hiddenElements.state.val
    ue
  • document.customerInfo.state.value
  • parent.topframe.document.hiddenElements.zip.value
  • document.customerInfo.zip.value
  • parent.topframe.document.hiddenElements.email.val
    ue
  • document.customerInfo.email.value
  • parent.topframe.document.hiddenElements.password.
    value
  • document.customerInfo.password.value

13
Example
  • More of the first form page page
  • if (document.customerInfo.platform0.checked
    true)
  • parent.topframe.document.hiddenElements.platform
    .value
  • document.customerInfo.platform0.value
  • if (document.customerInfo.platform1.checked
    true)
  • parent.topframe.document.hiddenElements.platform
    .value
  • document.customerInfo.platform1.value
  • if (document.customerInfo.platform2.checked
    true)
  • parent.topframe.document.hiddenElements.platform
    .value
  • document.customerInfo.platform2.value
  • // continue with the rest of the
    elements parent.topframe.document.hiddenElements.l
    ocation.value
  • document.customerInfo.location.value
  • parent.topframe.document.hiddenElements.comments.
    value
  • document.customerInfo.comments.value

14
Example
  • More of the first form page page
  • if (parent.topframe.document.hiddenElements.name
    .value ""
  • parent.topframe.document.hiddenElements.addre
    ss.value ""
  • parent.topframe.document.hiddenElements.city.
    value ""
  • parent.topframe.document.hiddenElements.state
    .value ""
  • parent.topframe.document.hiddenElements.zip.v
    alue ""
  • parent.topframe.document.hiddenElements.passw
    ord.value "")
  • alert("You must fill in the name, address,
    city, state, zip, and password fields.")
  • else
  • location.href"ProductInfo.html"
  • // STOP HIDING FROM INCOMPATIBLE BROWSERS --gt
  • lt/SCRIPTgt
  • lt/HEADgt

15
Example
  • More of the first form page page
  • ltBODYgt
  • ltH3gtCustomer Informationlt/H3gt
  • ltFORM NAME"customerInfo" onReset"return
    confirmReset()"gt
  • ltPgtNameltBRgt
  • ltINPUT TYPE"text" NAME"name" SIZE50gtlt/Pgt
  • ltPgtAddressltBRgt
  • ltINPUT TYPE"text" NAME"address" SIZE50gtlt/Pgt
  • ltPgtCity, State, ZipltBRgt
  • ltINPUT TYPE"text" NAME"city" SIZE38gt
  • ltINPUT TYPE"text" NAME"state" SIZE2
    MAXLENGTH2gt
  • ltINPUT TYPE"text" NAME"zip" SIZE5
    MAXLENGTH5gtlt/Pgt
  • ltPgtE-MailltBRgt
  • lt!-- put the rest of the elements in here --gt
  • ltPgtltINPUT TYPE"reset"gt
  • ltINPUT TYPE"button" NAME"next" VALUE" Next "
  • onClick"nextForm()"gtlt/Pgt
  • lt/FORMgt
  • lt/BODYgtlt/HTMLgt

16
Using Hidden Fields to Pass Info
  • Examples
  • MathQuiz.html. (using hidden fields)
  • ProductRegistration.html. (using hidden fields
    for creating a multiple page form). Second form
    page is ProductInfo.html.
  • Calculator.html. (hidden fields etc.)

17
Saving State Information with Query Strings
  • A query string
  • Set of namevalue pairs appended to a target URL
  • Consists of a single text string containing one
    or more pieces of information
  • To pass information from one Web page to another
    using a query string
  • Add a question mark (?) immediately after a URL,
    followed by the query string (in namevalue
    pairs) for the information you want to preserve

18
Manipulating Strings
  • Parsing
  • Refers to the act of extracting characters or
    substrings from a larger string
  • Essentially the same concept as the parsing
    (rendering) that occurs in a Web browser

19
The String Object
  • String object
  • Represents all literal strings and string
    variables in JavaScript
  • Contains methods for manipulating text strings
  • Length property returns the number of characters
    in a string

20
The String Object (Cont.)
21
The String Object (Cont.)
22
Parsing a String
  • The first parsing task
  • Remove question mark at the start of query string
  • Use substring() method combined with length
    property
  • Substring() method takes two arguments
  • Starting index number and an ending index number
  • The first character in a string has an index
    number of 0

23
Parsing a String (Cont.)
  • The next step
  • Convert individual pieces of information in
    queryData variable into array elements using the
    split() method
  • Pass to the split() method the character that
    separates each individual piece of information in
    a string

24
Query Strings Example
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtClientDoclt/TITLEgt
  • ltSCRIPT LANGUAGE"JavaScript"gt
  • lt!-- HIDE FROM INCOMPATIBLE BROWSERS
  • function createQueryString()
  • var queryString "ServerDoc.html?"
  • "firstName" document.info.firstName.value
  • "lastName" document.info.lastName.value
  • "occupation" document.info.occupation.valu
    e
  • location.href queryString
  • return false
  • // STOP HIDING --gt
  • lt/SCRIPTgt
  • lt/HEADgt

Client Page
ltBODYgt ltH2gtClient Doclt/H2gt ltFORM NAME"info"
onSubmit"return createQueryString()"gt ltPgtFirst
Name nbspltINPUT TYPE"text" NAME"firstName"gtltBR
gt Last Name nbspltINPUT TYPE"text"
NAME"lastName"gtlt/Pgt ltPgtOccupation nbspltINPUT
TYPE"text" NAME"occupation"gtlt/Pgt ltPgtltINPUT
TYPE"submit"gtlt/Pgt lt/FORMgtlt/BODYgtlt/HTMLgt
25
Query Strings Example
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtServerDoclt/TITLEgt
  • ltSCRIPT LANGUAGE"JavaScript"gt
  • lt!-- HIDE FROM INCOMPATIBLE BROWSERS
  • function parseQueryString()
  • var queryString location.search
  • var queryArray queryString.split("")
  • var first_name queryArray0.substring(queryArr
    ay0.indexOf("") 1,
  • queryArray0.length)
  • var last_name queryArray1.substring(queryArra
    y1.indexOf("") 1,
  • queryArray1.length)
  • var occupation queryArray2.substring(queryArr
    ay2.indexOf("") 1,
  • queryArray2.length)
  • document.info.firstName.value first_name
  • document.info.lastName.value last_name
  • document.info.occupation.value occupation
  • // STOP HIDING FROM INCOMPATIBLE BROWSERS --gt

Server Page
26
Query Strings Example
  • ltBODY onLoad"parseQueryString()"gt
  • ltH2gtServer Doclt/H2gt
  • ltFORM NAME"info"gt
  • ltPgtFirst Name nbspltINPUT TYPE"text"
    NAME"firstName"gtltBRgt
  • Last Name nbspltINPUT TYPE"text"
    NAME"lastName"gtlt/Pgt
  • ltPgtOccupation nbspltINPUT TYPE"text"
    NAME"occupation"gtlt/Pgt
  • ltPgtltINPUT TYPE"submit"gtlt/Pgt
  • lt/FORMgt
  • lt/BODYgt
  • lt/HTMLgt

Server Page Continued
27
Saving State information with Cookies
  • Query strings do not permanently maintain state
    information
  • Information available only during current Web
    page session
  • Hidden form fields maintain state information
    between Web pages
  • The data they contain are lost once the Web page
    that reads the hidden fields closes

28
Saving State information with Cookies (Cont.)
  • You can save the contents of a query string or
    hidden form fields
  • Submit the form data using a server-side
    scripting language
  • Requires separate server-based application

29
Saving State information with Cookies (Cont.)
  • To make it possible to store state information
    beyond the current Web page session, Netscape
    created cookies
  • Cookies
  • Small pieces of information about a user stored
    by a Web server in text files on the users
    computer

30
Saving State information with Cookies (Cont.)
  • Each time the Web client visits a Web server
  • Saved cookies for the requested Web page are sent
    from the client to the server
  • Server then uses cookies to customize the Web
    page for the client

31
Saving State information with Cookies (Cont.)
  • Cookies belong to the web page.
  • When you retrieve a cookie, all cookies
    associated with that web page are retrieved.
  • By default, a cookie is associated with, and
    accessible to, the web page that created it and
    any other web pages in the same directory or any
    subdirectories of that directory
  • You can change this association with the path
    attribute.

32
Saving State information with Cookies (Cont.)
  • Cookies can be temporary or persistent
  • Temporary cookies remain available only for the
    current browser session
  • Persistent cookies remain available beyond the
    current browser session
  • Stored in a text file on a client computer

33
Creating Cookies
  • You use the cookie property of the Document
    object to create cookies in namevalue pairs
  • The syntax for the cookie property is as follows
  • document.cookie name value
  • Normally assigning a value to a property causes
    the old value to be replaced
  • With cookies, assigning a new value to the cookie
    property builds a list of cookies.
  • Old cookies are not replaced

34
Creating Cookies
  • Example
  • Document.cookie firstName John
  • Document.cookie lastName Barr
  • Document.cookie occupation Prof
  • This automatically results in one cookie with 3
    values stored in it
  • firstNameJohn lastNameBarr occupationProf
  • The semicolons and spaces are added automatically
    by javascript.

35
Creating Cookies
  • The cookie property is created with a required
    name attribute and four optional attributes
  • Expires
  • Path
  • Domain
  • Secure

36
The name attribute
  • Only required parameter of the cookie property
  • Specifies the cookies namevalue pair
  • Cookies created with only the name attribute are
    temporary cookies
  • Available for only the current browser session

37
The name attribute (Cont.)
  • Cookies themselves cannot include semicolons or
    other special characters, such as commas or
    spaces
  • Transmitted between Web browsers and Web servers
    using HTTP
  • Does not allow certain non-alphanumeric
    characters to be transmitted in their native
    format

38
The name attribute (Cont.)
  • You can use special characters in your cookies if
    you use encoding
  • Involves converting special characters in a text
    string to their corresponding hexadecimal ASCII
    value, preceded by a percent sign

39
The name attribute (Cont.)
  • The built-in encodeURI() function is used in
    JavaScript for encoding text strings into a valid
    URI
  • The syntax for the encodeURI() function is
  • encodeURI(text)

40
The name attribute (Cont.)
  • Example creating three cookies for one site
  • itemCookie "itemsports coat"
  • styleCookie "styledouble breasted"
  • sizeCookie "size44 Regular"
  • document.cookie encodeURI(itemCookie)
  • document.cookie encodeURI(styleCookie)
  • document.cookie encodeURI(sizeCookie)

41
Reading Cookies
  • To read a cookie, you must
  • Retrieve the cookie.
  • When you retrieve a cookie, all cookies
    associated with that web directory are retrieved.
  • By default, a cookie is associated with, and
    accessible to, the web page that created it and
    any other web pages in the same directory or any
    subdirectories of that directory
  • Decode it using the decodeURI() function
  • Use the methods of the String object to extract
    individual namevalue pairs

42
The name attribute (Cont.)
  • Example extracting three values from a cookie
  • var purchaseData decodeURI(document.cookie)
  • var cookieString ""
  • if (purchaseData.length gt 0)
  • purchaseArray purchaseData.split(" ")
  • for (var i 0 i lt purchaseArray.length i)
  • cookieString purchaseArrayi "ltBRgt"
  • document.write(cookieString)
  • else
  • document.write("No stored purchase data.")

The characters are not included in the array
entries when the string is split
43
Cookie Attributes
  • The cookie property is created with a required
    name attribute and four optional attributes
  • Expires
  • Path
  • Domain
  • Secure
  • These attributes are appended to the
    nameattribute, but are separated by a semicolon
    and a space
  • document.cookie encodeURI(firstNameJohn)
    Mon Dec 27 141518 PST 2003

Note the semicolon and a space
44
The Expires attribute
  • For a cookie to persist beyond the current
    browser session
  • Use the expires attribute of the cookie property
  • The expires attribute of the cookie property
  • Determines how long a cookie can remain on a
    client system before it is deleted
  • Cookies created without an expires attribute are
    available for only the current browser session

45
The Expires attribute (Cont.)
  • Syntax for assigning the expires attribute to the
    cookie property, along with an associated
    namevalue pair
  • expiresdate
  • The namevalue pair and the expiresdate pair are
    separated by a semicolon and a space

46
The Expires attribute (Cont.)
  • Date must be Coordinated Universal Time (called
    UTC or Greenwich Mean Time (GMT) or Zulu time)
  • Weekday Month DD HHMMSS Time Zone YYYY
  • For example
  • Mon Dec 27 141518 PST 2003
  • Do not use the encodeURI() method for the date.
    Javascript will not be able to set the expiration
    date if you do.
  • Can manually type a string in UTC format or can
    create the string with the Date object.
  • Date object will automatically create the string
    in UTC format.
  • Note that the date created with the Date string
    will be in a slightly different format than given
    above. Either format will work.

47
Date Object
  • Contains methods and properties for manipulating
    the date and time
  • The Date object allows you to use the current
    date and time in your JavaScript programs
  • You create a new instance of the Date class using
    the syntax var dateObject new Date()

48
Date Class (Cont.)
49
The Expires attribute (Cont.)
  • Using the Date object
  • Use the set and get methods of the Date
    object
  • Example create a Date object and set it to
    expire in a year
  • var expiresDate new Date( )
  • expiresDate.setFullYear(expiresDate.getFullYear
    ( ) 1)
  • document.cookie encodeURI(firstNameJohn)
    expires expiresDate.toUTCString( )

50
The Path attribute
  • The path attribute
  • Determines the availability of a cookie to other
    Web pages on a server
  • Assigned to the cookie property, along with an
    associated namevalue pair, using the syntax
  • pathpath name

51
The Path attribute (Cont.)
  • By default, a cookie is available to all Web
    pages in the same directory
  • If a path is specified
  • Then a cookie is available to all Web pages in
    the specified path AND all Web pages in all
    subdirectories in the specified path

52
The Domain attribute
  • Using the path attribute allows cookies to be
    shared across a server
  • The domain attribute is used for sharing cookies
    across multiple servers in the same domain

53
The Domain attribute (Cont.)
  • Cookies cannot be shared outside of a domain
  • The domain attribute is assigned to the cookie
    property, along with an associated namevalue
    pair, using the syntax domaindomain name

54
The secure attribute
  • Indicates that a cookie can only be transmitted
    across a secure Internet connection using HTTPS
    or another security protocol
  • Generally when working with client-side
    JavaScript
  • Secure attribute should be omitted

55
The secure attribute (cont.)
  • If you wish to use the secure attribute
  • Assign it to the cookie property with a Boolean
    value of true or false, along with an associated
    namevalue pair, using the syntax secureboolean
    value

56
Using Cookies
  • Examples
  • http//www.ithaca.edu/faculty/barr/Student/CS205/E
    xamples/Tutorial09/ClientDoc2.html Using cookies
    to pass information to another web page
  • http//www.ithaca.edu/faculty/barr/Student/CS205/E
    xamples/Tutorial09/PurchaseCookies.html Saving
    purchase info with a cookie
  • http//www.ithaca.edu/faculty/barr/Student/CS205/E
    xamples/Tutorial09/LastVisit.html Saving the
    time last visited in a cookie
  • http//www.ithaca.edu/faculty/barr/Student/CS205/E
    xamples/Tutorial09/Counter.html Counting how many
    time youve visited using cookies.

57
Reading Cookies
  • Examples (continues)
  • http//www.ithaca.edu/faculty/barr/Student/CS205/E
    xamples/Tutorial09/NagCounter.html Nagging
    unregistered visitors.
  • http//www.ithaca.edu/faculty/barr/Student/CS205/E
    xamples/Tutorial09/Password.html Password
    protecting a site (after three failures you get
    in anyway!)
  • http//www.ithaca.edu/faculty/barr/Student/CS205/E
    xamples/Tutorial09/FavoriteBackground.html
    Remembering a visitors favorite background color.

58
JavaScript Security concerns
  • Security areas of most concern to JavaScript
    programmers are
  • 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
  • Privacy of individual client information in the
    Web browser window

59
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
  • For windows and frames to view and modify
    elements and properties of documents displayed in
    other windows and frames
  • Must have the same protocol (such as HTTP)
  • Must exist on the same Web server

60
The same origin Policy (cont.)
  • Applies not only to the domain name
  • Also to the server on which a document is located
  • Prevents
  • Malicious scripts from modifying the content of
    other windows and frames
  • Theft of private browser information and
    information displayed on secure Web pages

61
Chapter Summary
  • State information
  • Information about individual visits to a Web site
  • HTTP
  • Originally designed to be stateless
  • Web browsers stored no persistent data about a
    visit to a Web site

62
Chapter Summary (cont.)
  • Hidden form field
  • Special type of form element
  • Not displayed by the Web browser
  • Used to hide information from users
  • Form fields, query strings, and cookies
  • Most common tools for maintaining state
    information

63
Chapter Summary (cont.)
  • A query string
  • Set of namevalue pairs appended to a target URL
  • The String object
  • Contains methods for manipulating text strings
  • Cookies
  • Small pieces of information about a user stored
    by a Web server in text files on the users
    computer

64
Chapter Summary (cont.)
  • EncodeURI() function
  • Used in JavaScript for encoding text strings into
    a valid URI
  • DecodeURI() function
  • Decodes a cookie or other text string encoded
    with the encodeURI() function

65
Chapter Summary (cont.)
  • 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
  • Domain property of the Document object changes
    the origin of a document to its root domain name
Write a Comment
User Comments (0)
About PowerShow.com