(Some from Chapter 11.9 – “Web” 4 th edition and https://docs.python.org/3/library/http.cookies.html

Slides:



Advertisements
Similar presentations
LIS651 lecture 3 taming PHP Thomas Krichel
Advertisements

LIS651 lecture 3 functions & sessions Thomas Krichel
Presenter: James Huang Date: Sept. 29,  HTTP and WWW  Bottle Web Framework  Request Routing  Sending Static Files  Handling HTML  HTTP Errors.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing.
Cookies The HTTP protocol is stateless, that is, it does not maintain information on states after the session ends. But sometimes it is useful to remember.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming cookies.
JavaScript Forms Form Validation Cookies. What JavaScript can do  Control document appearance and content  Control the browser  Interact with user.
JavaScript Forms Form Validation Cookies CGI Programs.
Session Management A290/A590, Fall /25/2014.
CGI Programming: Part 1. What is CGI? CGI = Common Gateway Interface Provides a standardized way for web browsers to: –Call programs on a server. –Pass.
CGI programming Using Apache. Concepts Browser prepares parameter list List is attached to name of program to run on server "submit" button sends string.
Introduction to scripting
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
Client-Side programming with JavaScript 3
Chapter 9 Using Perl for CGI Programming. Computation is required to support sophisticated web applications Computation can be done by the server or the.
Web forms in PHP Forms Recap  Way of allowing user interaction  Allows users to input data that can then be processed by a program / stored in a back-end.
JavaScript: Control Structures September 27, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel, Deitel,
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
Cookies Set a cookie – setcookie() Extract data from a cookie - $_COOKIE Augment user authentication script with a cookie.
CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
Review and Practice for Final exam. Final exam Date: December 20, 3:15 – 5:15pm Format: Two parts: First part: multiple-choice questions (15 questions.
Comp2513 Forms and CGI Server Applications Daniel L. Silver, Ph.D.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
PHP Hypertext PreProcessor. Documentation Available SAMS books O’Reilly Books.
CSCI 6962: Server-side Design and Programming Secure Web Programming.
Chapter 9 Web Applications. Web Applications are public and available to the entire world. Easy access to the application means also easy access for malicious.
Cookies and Security Saving the “state”
JavaScript, Fourth Edition
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
Week 9 PHP Cookies and Session Introduction to JavaScript.
USING PERL FOR CGI PROGRAMMING
Chapter 8 Cookies And Security JavaScript, Third Edition.
Week seven CIT 354 Internet II. 2 Objectives Database_Driven User Authentication Using Cookies Session Basics Summary Homework and Project 2.
Using Client-Side Scripts to Enhance Web Applications 1.
An Introduction to JavaScript Summarized from Chapter 6 of “Web Programming: Building Internet Applications”, 3 rd Edition.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Regular Expression (continue) and Cookies. Quick Review What letter values would be included for the following variable, which will be used for validation.
Website Development with PHP and MySQL Saving Data.
1 Basic Perl CGI Programming. 2 Issues How and when your program is invoked. Generating Response –HTTP Headers –HTML (or whatever document type you want)
Cookies Web Browser and Server use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website it is required to maintain.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
ITM © Port, Kazman1 ITM 352 More on Forms Processing.
הרצאה 4. עיבוד של דף אינטרנט דינמי מתוך Murach’s PHP and MySQL by Joel Murach and Ray Harris.  דף אינטרנט דינמי משתנה עפ " י הרצת קוד על השרת, יכול להשתנות.
ECMM6018 Enterprise Networking for Electronic Commerce Tutorial 7
Cookies (continue). Extracting Data From Cookies Data retrieved from a cookie is a simple text string. While there is no specific JavaScript function.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
 Previous lessons have focused on client-side scripts  Programs embedded in the page’s HTML code  Can also execute scripts on the server  Server-side.
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
1 State and Session Management HTTP is a stateless protocol – it has no memory of prior connections and cannot distinguish one request from another. The.
(see online resources, e.g. SY306 Web and Databases for Cyber Operations Slide Set #9: CGI with Python.
5 th ed: Chapter 17 4 th ed: Chapter 21
Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing a Line of Text in a Web Page 7.3 Another JavaScript.
IS2802 Introduction to Multimedia Applications for Business Lecture 8: JavaScript and Cookies Rob Gleasure
Project 5: Customizing User Content Essentials for Design JavaScript Level Two Michael Brooks.
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
JavaScript: A short introduction Joseph Lee Created by Joseph Lee.
PHP: Further Skills 02 By Trevor Adams. Topics covered Persistence What is it? Why do we need it? Basic Persistence Hidden form fields Query strings Cookies.
INTERNET APPLICATIONS CPIT405 JavaScript Instructor: Rasha AlOmari
Some from Chapter 11.9 – “Web” 4 th edition and SY306 Web and Databases for Cyber Operations Cookies and.
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
SlideSet #20: Input Validation and Cross-site Scripting Attacks (XSS) SY306 Web and Databases for Cyber Operations.
Java Script: Objects (Chapter 12 in [2]). 2 Outline Introduction Introduction Thinking About Objects Thinking About Objects Math Object Math Object String.
11 JavaScript: Objects.
CS 330 Class 7 Comments on Exam Programming plan for today:
Play Framework: Introduction
Web Systems Development (CSC-215)
WEB PROGRAMMING JavaScript.
JavaScript: Introduction to Scripting
PHP-II.
Presentation transcript:

(Some from Chapter 11.9 – “Web” 4 th edition and ) SY306 Web and Databases for Cyber Operations Cookies: JavaScript and Python

Cookies Example

JavaScript: Using Cookies Cookie –Data stored on _____________ to maintain information about client during and between browser sessions –A string: identifier=value pairs separated by ; –Can be accessed through document.cookie property –Set expiration date using expires keyword –Use escape or encodeURI function to convert non- alphanumeric characters to hexadecimal escape sequences –unescape or decodeURI function converts hexadecimal escape sequences back to English characters

Storing Cookies – Simple Version document.writeln(" Cookie is: "+document.cookie); document.cookie = "name=" + escape("J Smith"); document.writeln(" Cookie is: "+document.cookie); document.cookie = "rank=" + escape("Captain"); document.writeln(" Cookie is: "+document.cookie);

Reading Cookies – Simple Version myCookies = document.cookie; cookieElements = myCookies.split("="); document.writeln( " Identifier stored is: "+ cookieElements[0] + " Value stored is: " + cookieElements[1]);

Simple Cookie Example // reset the document's cookie if wrong person function wrongPerson() { // reset the cookie document.cookie= "name=null;" + " expires=Thu, 01-Jan-95 00:00:01 GMT"; // after removing the cookie reload the page to get a new name location.reload(); } // determine whether there is a cookie if ( document.cookie ) { var cookie = document.cookie; var cookieTokens = cookie.split( "=" ); // set name to the part of the cookie that follows the = sign name = cookieTokens[ 1 ]; name = unescape(name); } else { // if there was no cookie then ask the user to input a name name = window.prompt( "Please enter your name", “Paul" ); document.cookie = "name=" + escape( name ); } document.writeln(" Hello, " +name + ". " ); document.writeln( “ " + "Click here if you are not " + name + " " );

Exercise #1: JS: Ask user for favorite quote using a window prompt. Save quote in a cookie identified by “favQuote”. Display quote on the page.

Storing Cookies – More Realistic By default, cookies expire when session ends Set “expires” attribute to make stick around longer function createCookie(identifier,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = identifier+"="+escape(value)+expires; } function eraseCookie(identifier) { createCookie(identifier,"",-1); } (modified from

Reading Cookies – More Realistic // Return the 'value' of the cookie with identifier 'desiredId' // returns null if no match found. function readCookie(desiredId) { // First split the pairs apart on '; ' var pairs = document.cookie.split("; "); // Now split each pair on '='. Check if have a match for (var i=0; i < pairs.length; i++) { var aPair = pairs[i]; // split into desired parts and check for match var cookieTokens = aPair.split("="); var id = cookieTokens[0]; var value = cookieTokens[1]; if (id == desiredId) { // found desired cookie -- return value return unescape(value); } return null; // no match }

Exercise #2: JS: Read the value of cookie identified by “favQuote” and display it in a pop-up msg if it exists, otherwise display “no quotes”

Exercise #3: Re-write Simple Cookie Example using the helper functions

Cookies – Java Script and Python Cookies with JavaScript –Create cookie document.cookie = “color=red”; –Read cookie (from JavaScript) Read and parse document.cookie Use readCookie() function to help with this –Where are cookies stored?? Cookies with Python –Create cookie with print() BEFORE printing “Content-type …” Sent to browser –Browser always sends appropriate cookies back to server with request –Read cookie Access “HTTP_COOKIE” environment variable (from os import environ) Use SimpleCookie class (from http import cookies) –Where are cookies stored?? Cookies created with Python can be read via JavaScript and vice versa

Create Cookies with Python (Assume this file invoked from a HTML form with fields name, and color) #!/usr/bin/env python3 from http import cookies import urllib.parse, cgi, cgitb #get parameters params = cgi.FieldStorage() name = params.getvalue("name") height = params.getvalue("height") color = params.getvalue("color") #set cookies #set expiration time in 1 hour expires = 60*60; mycookie = cookies.SimpleCookie() mycookie["Name"] = name mycookie["Color"] = color mycookie["Color"]['expires']= expires print (mycookie) #BEFORE content-type line print( "Content-type:text/html\n"); set10_createCookies.py – part1

print (""“ Storing cookies 2 cookies were stored! ""“) print (" Name: "+ name + " Color: "+color + " "); print(" "); set10_createCookies.py – part2

Read Cookies With Python #!/usr/bin/env python3 from http import cookies import os #read cookies name = "" color = "" if 'HTTP_COOKIE' in os.environ: cookie_string=os.environ.get('HTTP_COOKIE') mycookie=cookies.SimpleCookie() mycookie.load(cookie_string) try: name=mycookie['Name'].value color = mycookie['Color'].value except KeyError: name="" print ("Content-type: text/html\n") set10_readCookies.py – part1

print ("""\ Reading cookies """) if name or color: print (" Cookies found! "); print (" Name: "+name+" "); print (" Color: " + color +" "); else: print (" Could not find cookies for Name or Color ") ; print(" "); set10_readCookies.py – part2

Uses for Cookies Most common: –User logs in using secure page (https) –Server checks password. If good, creates cookie E.g. “login=m168987&auth=356af12cd124552” –User redirected to other pages. These pages don’t ask for password – instead just check that have valid login cookie –Why do we need the auth field?

Exercise #4: Python: a) Create a cookie with identifier “favQuote” and content “DTT/FSA” b) change your program to store the quote provided by user (not hardcoded) through CGI – param name “quote”

Remember Relevant cookies always sent by browser to the server Can create with JavaScript and read with Python Or create with Python and read with JavaScript