Google App Engine Sessions and Cookies ae-09-session www.appenginelearn.com.

Slides:



Advertisements
Similar presentations
CookiesPHPMay-2007 : [‹#›] Maintaining State in PHP Part I - Cookies.
Advertisements

UFCE8V-20-3 Information Systems Development 3 (SHAPE HK)
Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
Web, HTTP and Web Caching
Definitions, Definitions, Definitions Lead to Understanding.
Session Management A290/A590, Fall /25/2014.
Application Layer  We will learn about protocols by examining popular application-level protocols  HTTP  FTP  SMTP / POP3 / IMAP  Focus on client-server.
HTTP Overview Vijayan Sugumaran School of Business Administration Oakland University.
1 The World Wide Web. 2  Web Fundamentals  Pages are defined by the Hypertext Markup Language (HTML) and contain text, graphics, audio, video and software.
2/9/2004 Web and HTTP February 9, /9/2004 Assignments Due – Reading and Warmup Work on Message of the Day.
Forms and PHP Dr. Charles Severance
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
Cookies, Sessions, and Authentication Dr. Charles Severance
_______________________________________________________________________________________________________________ E-Commerce: Fundamentals and Applications1.
ITIS 1210 Introduction to Web-Based Information Systems Chapter 48 How Internet Sites Can Invade Your Privacy.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
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.
Comp2513 Forms and CGI Server Applications Daniel L. Silver, Ph.D.
2: Application Layer1 CS 4244: Internet Software Development Dr. Eli Tilevich.
Working with Cookies Managing Data in a Web Site Using JavaScript Cookies* *Check and comply with the current legislation regarding handling cookies.
CSE 154 LECTURE 12: COOKIES. Including files: include include("filename"); PHP include("header.html"); include("shared-code.php"); PHP inserts the entire.
Parent Guide for staying connected. To Begin using Skyward Family Access you will need:  A computer connected to the internet  A web browser (Windows.
Week seven CIT 354 Internet II. 2 Objectives Database_Driven User Authentication Using Cookies Session Basics Summary Homework and Project 2.
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
1 Maryland ColdFusion User Group Session Management December 2001 Michael Schuler
Mark Dixon 1 03 – Passing Data between pages: Forms, Sessions, & Query Strings.
Cookies & Session Web Technology
11 1 Cookies CGI/Perl Programming By Diane Zak Objectives In this chapter, you will: Learn the difference between temporary and persistent cookies.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
Google App Engine Using Templates Jim Eng Thanks to Chuck Severance
Google App Engine Data Store ae-10-datastore
CIS679: Lecture 13 r Review of Last Lecture r More on HTTP.
Web Database Programming Week 7 Session Management & Authentication.
Cookies and Sessions IDIA 618 Fall 2014 Bridget M. Blodgett.
A Little Bit About Cookies Fort Collins, CO Copyright © XTR Systems, LLC A Little Bit About Cookies Instructor: Joseph DiVerdi, Ph.D., M.B.A.
Google App Engine MemCache ae-09-session
Google Application Engine Introduction Jim Eng with thanks to Charles Severance
CP476 Internet Computing CGI1 Cookie –Cookie is a mechanism for a web server recall info of accessing of a client browser –A cookie is an object sent by.
ASP. What is ASP? ASP stands for Active Server Pages ASP is a Microsoft Technology ASP is a program that runs inside IIS IIS stands for Internet Information.
Jan 2001C.Watters1 World Wide Web and E-Commerce Client Side Processing.
ECMM6018 Enterprise Networking for Electronic Commerce Tutorial 7
Google App Engine References ae-11-chat
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.
©SoftMooreSlide 1 Session Tracking with Servlets.
SESSIONS 27/2/12 Lecture 8. ? Operator Similar to the if statement but returns a value derived from one of two expressions by a colon. Syntax: (expression)
PHP and Sessions. Session – a general definition The GENERAL definition of a session in the “COMPUTER WORLD” is: The interactions (requests and responses)
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 1: Introduction to IS2803 Rob Gleasure
1 DIG 3134 Lecture 6: Maintaining State Michael Moshell University of Central Florida Media Software Design.
ITM © Port,Kazman 1 ITM 352 Cookies. ITM © Port,Kazman 2 Problem… r How do you identify a particular user when they visit your site (or any.
Forms and PHP Dr. Charles Severance
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
IN THIS LESSON WE WILL REVIEW THE STRUCTURE OF THE INTERNET AND HOW BROWSERS ASSEMBLE WEBSITES BASED ON INSTRUCTIONS THEY RECEIVE FROM SERVERS. Internet.
COOKIES AND SESSIONS.
LOGIN FORMS.
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.
© Janice Regan, CMPT 128, Jan 2007 CMPT 371 Data Communications and Networking HTTP 0.
Distributed Web Systems Cookies and Session Tracking Lecturer Department University.
© Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● / www,histpk.org Hidaya Institute of Science & Technology
Managing State Chapter 13.
ITM 352 Cookies.
Cookies and Sessions Charles Severance
Client / Session Identification Cookies
Web Caching? Web Caching:.
What is Cookie? Cookie is small information stored in text file on user’s hard drive by web server. This information is later used by web browser to retrieve.
Cookies and sessions Saturday, February 23, 2019Saturday, February 23,
Back end Development CS Programming Languages for Web Applications
Back end Development CS Programming Languages for Web Applications
Presentation transcript:

Google App Engine Sessions and Cookies ae-09-session

Cookies and Sessions Maintaining State in HTTP

High Level Summary The web is “stateless” The browser does not maintain a connection to the server while you are looking at a page. You may never come back to the same server Or it may be a long time Or it may be one second later

High Level Summary The web is “stateless” So we need a way for servers to know “which browser is this?” In the browser, state is stored in “Cookies” In the server, state is stored in “Sessions”

Some Web sites always seem to want to know who you are!

Other Web sites always seem to know who you are!

Browser Server GET Whole Page GET Whole Page Draw You watch the YouTube video for an 30 seconds How you see YouTube... Click

Browser Server GET Whole Page GET Whole Page How YouTube sees you... Draw Click

Multi-User When a server is interacting with many different browsers at the same time, the server needs to know *which* browser a particular request came from Request / Response initially was stateless All browsers looked identical This was was fine for static web pages But it was really really bad for "webapps" Those simple days did not last very long at all.

Web Cookies to the Rescue Technically, cookies are arbitrary pieces of data chosen by the Web server and sent to the browser. The browser returns them unchanged to the server, introducing a state (memory of previous events) into otherwise stateless HTTP transactions. Without cookies, each retrieval of a Web page or component of a Web page is an isolated event, mostly unrelated to all other views of the pages of the same site.

Cookies In the Browser Cookies contain markers indicating the web addresses they come from The browser only sends a cookie to the web server that originally set it Cookies have an expiration date Some last for years Others are short-term and go away as soon as the browser is closed

Playing with Cookies Firefox's WebDeveloper plugin has a set of cookie features Other browsers have a way to view or change cookies

Cookies Identifying individual users across requests Making the web seem not to be stateless

Request / Response Again!

Browser Server GET Whole Page Fragment Redraw Update HTTP REQ HTTP REQ CookiesCookies Cookies Remember that cookies are only sent back to the host that set the cookie.

HTTP Request / Response Cycle Browser Web Server HTTP Request HTTP Response Internet Explorer, FireFox, Safari, etc. (Review)

HTTP Request / Response Cycle GET /index.html HTTP/1.1 Accept: www/source Accept: text/html User-Agent: Lynx/2.4 Browser Web Server HTTP Request We do our initial GET to a server. The server checks to see if we have a cookie with a particular name set. Since this is our first interaction, we have no cookies set for this host.

HTTP Request / Response Cycle Browser Web Server HTTP Response HTTP/ OK Content-type: text/html Set-Cookie: sessid=123.. Welcome.... host: sessid=123 Along with the rest of the response, the server sets a cookie with some name (sessid) and sends it back along with the rest of the response.

HTTP Request / Response Cycle GET /index.html HTTP/1.1 Accept: www/source Accept: text/html Cookie: sessid=123 User-Agent: Lynx/2.4 Browser Web Server HTTP Request host: sessid=123 From that point forward, each time we send a GET or POST to the server, we include any cookies which were set by that host.

HTTP Request / Response Cycle Browser Web Server HTTP Response HTTP/ OK Content-type: text/html Set-Cookie: name=chuck.. Welcome.... host: sessid=123 host:name=chuck On each response, the server can change a cookie value. Or add another cookie.

HTTP Request / Response Cycle GET /index.html HTTP/1.1 Accept: www/source Accept: text/html Cookie: sessid=123,name=Chuck User-Agent: Lynx/2.4 Browser Web Server HTTP Request From that point forward, each time we send a GET or POST to the server, we include all the cookies which were set by that host. host: sessid=123 host:name=chuck

Security We ony send cookies back to the host that originally set the cookie The browser has *lots* of cookies for lots of hosts To see all Cookies: Firefox -> Preferences -> Privacy -> Show Cookies

The Firefox Web Developer Plugin Shows Cookies for the Current Host.

Two Kinds of Cookies Long-lived - who you are - account name - last access time You can close and reopen your browser and it is still there Temporary - used to identify your session It goes away when you close the browser

Using Cookies to Support Sessions and Login / Logout

Some Web sites always seem to want to know who you are!

In The Server - Sessions In most server applications, as soon as we meet a new browser we create a session We set a session cookie to be stored in the browser which indicates the session id in use The creation and destruction of sessions is generally handled by a web framework or some utility code that we just use to manage the sessions

Session Identifier A large, random number that we place in a browser cookie the first time we encounter a browser. This number is used to pick from the many sessions that the server has active at any one time. Server software stores data in the session which it wants to have from one request to another from the same browser. Shopping cart or login information is stored in the session in the server

Server Session 97 Browser C cook=97 Request Response index:“Please log in” cook=97 Create Session

Server Session 97 Browser C cook=97 Typing We now have a session established but are not yet logged in.

Login / Logout Having a session is not the same as being logged in. Generally you have a session the instant you connect to a web site The Session ID cookie is set when the first page is delivered Login puts user information in the session (stored in the server) Logout removes user information from the session

Server Session 97 Browser C cook=97 Request login: if good: set user Click cook=97

Server Session 97 user=phil Browser C cook=97 Request login: if good: set user Click Response cook=97

Server Session 97 user=phil Browser C cook=97

Using Sessions for Other Stuff

Server Browser A cook=10 Browser B cook=46 Session 10 user=chuckbal=$1000 Session 46 user=janbal=$400

Server Session 10 user=chuckbal=$1000 Session 46 user=janbal=$500 Browser A cook=10 Browser B cook=46 withdraw:bal=bal-100

Server Session 10 user=chuckbal=$1000 Session 46 user=janbal=$500 Browser A cook=10 Browser B cook=46 withdraw:bal=bal-100 Click

Server Session 10 user=chuckbal=$1000 Session 46 user=janbal=$500 Browser A cook=10 Browser B cook=46 cook=46 withdraw:bal=bal-100

Server Session 10 user=chuckbal=$1000 Session 46 user=janbal=$400 Browser A cook=10 Browser B cook=46 cook=46 withdraw:bal=bal-100 Response Request

Review...

High Level Summary The web is “stateless” - the browser does not maintain a connection to the server while you are looking at a page. Yu may never come back to the same server - or it may be a long time - or it may be one second later So we need a way for servers to know “which browser is this?” In the browser state is stored in “Cookies” In the server state is stored in “Sessions”

Browser Server GET Whole Page GET Whole Page Draw You watch the YouTube video for an 30 seconds How you see YouTube... Click

Browser Server Draw Click GET Whole Page GET Whole Page

Browser Server Draw Click GET Whole Page GET Whole Page Session 42 cook=42 cook=42

Cookie/Session Summary Cookies take the stateless web and allow servers to store small “breadcrumbs” in each browser. Session IDs are large random numbers stored in a cookie and used to maintain a session on the server for each of the browsers connecting to the server Server software stores sessions *somewhere* - each time a request comes back in, the right session is retrieved based on the cookie Server uses the session as a scratch space for little things

Programming and Sessions

First Look: Sessions are Magic! Sessions are usually part of the built-in web application framework Ruby on Rails Java Web Applications PHP The framework does all the cookie setting and data finding

First Look: Sessions are Magic! In our controller code we simply ask to create and/or access a session We treat the session like a dictionary storing whatever we like in the session under a set of string keys that we choose

Session Rules Keep them small - we don’t want to put too much in the session or we start taxing memory and other storage resources and slowing down our application Focus on data that is used on nearly every incoming request - the lookup key of the current user - the address of the current user Sessions generally go away when the user closes their browser (cookie is lost) or after a period of inactivity (1-3 hours)

Session Uses Indication of the current user - management of the login and log out process Shopping cart - items / quantities

Our Magic - sessions.py Since the Google Application Engine does not provide a session capability, we need to add one - extending our application Download from Install in your application in the directory util to make it available in your application

Using the Session from util.sessions import Session class LogoutHandler(webapp.RequestHandler): def get(self): self.session = Session() self.session.delete('username') doRender(self, 'index.htm') The Session() call either establishes a session or accesses the current session.

Inside the Session() call We use a session cookie to look up our session If the cookie exists and the session exists, return that session If not pick a large random number as the session key, make a session and set a temporary cookie with the session key as its value

The Login/Logout Pattern We use a key named ‘username’ in the session to indicate that the user is logged in If the key is missing the user is logged out If the key is present, its value is the account of the logged in user (e.g. “csev”)

def post(self): self.session = Session() acct = self.request.get('account') pw = self.request.get('password') logging.info("Checking account="+acct+" pw="+pw) self.session.delete('username') if pw == "" or acct == "": doRender(self,"login.htm",{'error' : 'Please specify Acct/PW'} ) elif pw == "secret": self.session['username'] = acct doRender(self,"index.htm",{ } ) else: doRender(self,"login.htm",{'error' : 'Incorrect password'} ) Get the Session Log out previous user Log in new user

Logout from util.sessions import Session class LogoutHandler(webapp.RequestHandler): def get(self): self.session = Session() self.session.delete('username') doRender(self, 'index.htm') Get the Session Log out previous user

Navigation We want to have the Login / Logout button flip when we log in or out and we want to see the name of the current logged in user.

<a href="topics.htm" {% ifequal path '/topics.htm' %} class="selected" {% endifequal %} >Topics {% ifequal username None %} <a href="/login" {% ifequal path '/login' %} class="selected" {% endifequal %} >Login {% else %} Logout ({{username}}) {% endifequal %} In the view template, we send an additional context variable to the template called “username” if the user is logged in. We use logic in the template to either generate the Login link or the Logout + account name link. _base.htm

def doRender(self, tname = "index.htm", values = { }): logging.info(tname) temp = os.path.join(os.path.dirname(__file__),'templates/'+tname) if not os.path.exists(temp): return False # Make a copy of the dictionary and add basic values newval = dict(values) if not 'path' in newval: path = self.request.path newval['path'] = self.request.path if not 'username' in newval: self.session = Session() if 'username' in self.session: newval['username'] = self.session["username"] outstr = template.render(temp, newval) self.response.out.write(outstr) return True We check to see if the username is in the session and if username is in the session we add it to the context variables to be passed into the template.

Summary The Cookies and Session work together to give us a relatively simply way to programmatically stash data associated with a particular user/browser While the mechanisms are a bit complex, the session pattern turns out to be pretty simple to use in our applications The Google Application Engine does not provide us with a Session feature - so we need to write or borrow some code Clever use of session is important to application performance