SlideShare une entreprise Scribd logo
1  sur  19
Syllabus
Introduction: Web Development and Client Side Programming, Protocols Governing Web, Internet Services
and Tools, Client-Server Computing;
HTML: Basic Syntax, Standard HTML Document Structure, Basic Text Markup, Images, Hypertext Links, Lists,
Tables, Forms, HTML5;
CSS: Creating Style Sheets, Levels of Style Sheets, CSS Properties, Style Specification Formats, Selector Forms,
The Box Model, Conflict Resolution;
Javascript: Basics of Javascript, Variables, Arrays and Operators, Functions, Event Handlers, Built-in JS
Objects, Form Validations, Conditional and Loops, Storage and Cookies,Debugging and Testing;
Introduction to AJAX: AJAX and Node.Js Server, The Xmlhttprequest Object, Handling The Response, Jquery,
Passing Data, AJAX Application;
PHP Programming: Introduction to PHP, Creating PHP Script, Running PHP Script, Variables and Constants,
Data Types, Operators, Conditional Statements, Control Statements, Arrays, Functions, Working With Forms
and Databases Connection, Introduction to Web-Server and XAMPP.
1
Contents
• Introduction
• localStorage
• sessionStorage
• Cookies
2
Introduction
Data storage is crucial for creating dynamic, responsive, and
personalized user experiences
common methods to store data
•localStorage
•sessionStorage
•Cookies
localStorage
• localStorage is part of the Web Storage API
• provides a way to store data locally within the user's browser
• Data stored using localStorage is persistent across browser sessions, i.e no expiration time
• localStorage data for a document loaded in a "private browsing" or "incognito" session is cleared
when the last "private" tab is closed.
• keys and the values stored with localStorage are always in the UTF-16 string format (two bytes per
character)
• Integer keys are always converted to strings
localStorage.setItem(“myName”, “John”);
const name = localStorage.getItem(“myName”);
localStorage.removeItem(“myName");
localStorage.clear();
sessionStorage
• sessionStorage is similar to localStorage but with shorter lifecycle
• A session is created with each page opened in a tab
• Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window
• Duplicating a tab copies the tab's sessionStorage into the new tab
• page session lasts as long as the tab or the browser is open, and survives over page reloads and
restores
• data stored in sessionStorage is cleared when the page session ends (i.e., when the browser tab
is closed).
• sessionStorage creates different objects for different protocols (HTTP, HTTPS, FTP etc..)
// Save data to sessionStorage
sessionStorage.setItem("key", "value");
// Get saved data from sessionStorage
let data = sessionStorage.getItem("key");
// Remove saved data from sessionStorage
sessionStorage.removeItem("key");
// Remove all saved data from sessionStorage
sessionStorage.clear();
sessionStorage
// Get the text field that we're going to track
let field = document.getElementById("field");
// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if (sessionStorage.getItem("autosave")) {
// Restore the contents of the text field
field.value = sessionStorage.getItem("autosave");
}
// Listen for changes in the text field
field.addEventListener("change", () => {
// And save the results into the session storage object
sessionStorage.setItem("autosave", field.value);
});
Cookies
• An HTTP cookie (web cookie, browser cookie) is a small piece of data that a
server sends to a user's web browser.
• Browser stores the cookie and sends it back to the same server with later
requests
• Useful in identifying if two requests come from the same browser—keeping a
user logged in
• remembers stateful information for the stateless HTTP protocol
• Purposes of Cookies
◦ Session management: Logins, shopping carts, game scores, or
anything else the server should remember
◦ Personalization: User preferences, themes, and other settings
◦ Tracking: Recording and analyzing user behavior
Cookies
• Client sends a HTTP request
• Server responds with one or more set-cookie headers data and n HTTP cookie
(web cookie, browser cookie) is a small piece of data that a server sends to a
user's web browser.
• browser stores the cookie and sends it with requests made to the same server
inside a Cookie HTTP header
Cookies
Cookies can have expiration time
Set-cookie header format
Set-Cookie: <cookie-name>=<cookie-value>
Ex: Server sending 2 cookies
HTTP/2.0 200 OK
Content-Type: text/html
Set-Cookie: yummy_cookie=choco
Set-Cookie: tasty_cookie=strawberry
Client sending cookies to server with a request
GET /sample_page.html HTTP/2.0
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry
Cookies: Lifetime
Permanent cookies: are deleted at a date specified by the Expires (GMT String format)
attribute or after a period prescribed by the Max-Age (number of seconds) attribute.
If both Expires and Max-Age are set, Max-Age has precedence.
Session cookies – cookies without a Max-age or Expires attribute
Session cookies are deleted when the current session ends.
The browser defines when the "current session" ends
some browsers use session restoring when restarting.
Set-Cookie: id=a3fWa; Expires=Thu, 31 Oct 2021 07:28:00 GMT;
Set-Cookie: id=a3fWa; Max-Age=2592000
Cookies: Secure and HttpOnly
A cookie with the Secure attribute is only sent to the server with an encrypted request
over the HTTPS protocol
Secure cookies are never sent with unsecured HTTP (except on localhost).
Anyone with access to the client's hard disk or JavaScript can read and modify the cookies
To prevent access to cookies fro JavaScript, HttpOnly attribute is used
Set-Cookie: id=a3fWa; Expires=Thu, 21 Oct 2021 07:28:00 GMT;
Secure; HttpOnly
Cookies: Domain and Path attributes
• The Domain attribute of a cookie specifies which server can receive that cookie.
◦ Presence of Domain attribute:
cookies are available on main domain and its subdomains.
Ex: Domain=mozilla.org,
cookies are available on mozilla.org and its subdomains like
developer.mozilla.org
◦ Absence of Domain Attribute:
cookies are available only on main domain
• Invalid domain must be rejected by the browser
◦ Ex: following cookie sent by originalcompany.com must be rejected
◦ Set-Cookie: qwerty=219ffwef9w0f; Domain=somecompany.co.uk
• The Path attribute indicates a URL path that must exist in the requested URL in order to
send the Cookie.
◦ The %x2F ("/") character is considered a directory separator,
◦ Ex: Path=/docs, the matching request paths are
◦ /docs /docs/ /docs/Web/ /docs/Web/HTTP
Cookies: Domain and Path attributes
• The Path attribute indicates a URL path that must exist in the requested URL in order to
send the Cookie.
• If the Path attribute is not set, its default value is computed from the path of the URI that
set the cookie
◦ If the path is empty, does not start with "/", or contains no more than one "/" character, then the default
value for Path is "/".
◦ Ex: https://example.org or https://example.org/ the path is “/”
◦ Otherwise, the default value for Path is the path from the start up to but not including the final "/"
character
◦ Ex: https://example.org/a/b/c, Path would be "/a/b"
Cookies: SameSite attribute
• A site is defined by a registered domain name and a scheme (http or https)
◦ Ex: https://jaipur.manipal.edu/
• The SameSite attribute lets servers specify whether/when cookies are sent with cross-site
requests.
• Three values are set for the SameSite attribute
◦ Strict: browser only sends the cookie with requests from the cookie's origin site
◦ Ex: Cookies from https://jaipur.manipal.edu/ are sent only to https://jaipur.manipal.edu/
◦ Lax: Similar to Strict but user can reach origin page by navigation (or redirection)
◦ Doesn’t work with cross-site requests (Ex: accessing images or resources)
◦ Ex: Navigation to https://jaipur.manipal.edu/ via Google search
◦ manipal.edu home page requesting an image from https://images.google.com/ is a cross-site request
◦ None: Cookies are sent on both originating and cross-site requests, but only in secure contexts
◦ if SameSite=None then the Secure attribute must also be set
• If no SameSite attribute is set, the cookie is treated as Lax (default value)
Set-Cookie: mykey=myvalue; SameSite=Strict
Cookies: SameSite attribute
Set-Cookie: <cookie-name>=<cookie-value>
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>
Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly
Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<number>
Set-Cookie: <cookie-name>=<cookie-value>; Partitioned
Set-Cookie: <cookie-name>=<cookie-value>; Path=<path-value>
Set-Cookie: <cookie-name>=<cookie-value>; Secure
Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Strict
Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Lax
Set-Cookie: <cookie-name>=<cookie-value>; SameSite=None; Secure
// Multiple attributes are also possible, for example:
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly
Cookies: Creation
document.cookie = "yummy_cookie=choco";
document.cookie = "tasty_cookie=strawberry";
console.log(document.cookie);
// logs "yummy_cookie=choco; tasty_cookie=strawberry"
Cookies created via JavaScript can't include the HttpOnly flag
Cookies available to JavaScript can be stolen through XSS
HttpOnly attribute prevents XSS attacks
Cookies used for sensitive information (such as authentication) should have a
short lifetime, with the SameSite attribute set to Strict or Lax
Cookies
Read all cookies accessible from current session
allCookies = document.cookie;
document.cookie returns a string containing a semicolon-separated list of all
cookies (i.e. key=value pairs)
document.cookie = "name=oeschger; SameSite=None; Secure";
document.cookie = "favorite_food=tripe; SameSite=None; Secure";
function showCookies() {
const output = document.getElementById("cookies");
output.textContent = `> ${document.cookie}`;
}
function clearOutputCookies() {
const output = document.getElementById("cookies");
output.textContent = "";
}
Cookies
document.cookie = "test1=Hello; SameSite=None; Secure";
document.cookie = "test2=World; SameSite=None; Secure";
const cookieValue = document.cookie.split("; ").find((row) =>
row.startsWith("test2="))?.split("=")[1];
function showCookieValue() {
const output = document.getElementById("cookie-value");
output.textContent = `> ${cookieValue}`;
}
function clearOutputCookieValue() {
const output = document.getElementById("cookie-value");
output.textContent = "";
}
Cookies
Writing/Updating a Cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 9999 23:59:59 GMT;
path=/";
cookie attribute values optionally follow the key-value pair, each preceded by a
semicolon separator.
Reading a Cookie
const cookies = document.cookie.split('; ');
const usernameCookie = cookies.find(cookie => cookie.startsWith('username='));
const username = usernameCookie.split('=')[1];
Deleting Cookie
• You can delete a cookie by updating its expiration time to past date or max-age to zero or negative value

Contenu connexe

Similaire à 19_JavaScript - Storage_Cookies_students.pptx

Optimising Web Application Frontend
Optimising Web Application FrontendOptimising Web Application Frontend
Optimising Web Application Frontend
tkramar
 
Ch4(saving state with cookies and query strings)
Ch4(saving state with cookies and query strings)Ch4(saving state with cookies and query strings)
Ch4(saving state with cookies and query strings)
Chhom Karath
 
ASP.Net Presentation Part3
ASP.Net Presentation Part3ASP.Net Presentation Part3
ASP.Net Presentation Part3
Neeraj Mathur
 
07 cookies
07 cookies07 cookies
07 cookies
snopteck
 

Similaire à 19_JavaScript - Storage_Cookies_students.pptx (20)

Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Cookies & Session
Cookies & SessionCookies & Session
Cookies & Session
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
State Management.pptx
State Management.pptxState Management.pptx
State Management.pptx
 
Java script Advance
Java script   AdvanceJava script   Advance
Java script Advance
 
Session 32 - Session Management using Cookies
Session 32 - Session Management using CookiesSession 32 - Session Management using Cookies
Session 32 - Session Management using Cookies
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
 
ASP.NET Lecture 2
ASP.NET Lecture 2ASP.NET Lecture 2
ASP.NET Lecture 2
 
Notes on SF W3Conf
Notes on SF W3ConfNotes on SF W3Conf
Notes on SF W3Conf
 
Overview of Cookies in HTTP - Miran al Mehrab
Overview of Cookies in HTTP - Miran al MehrabOverview of Cookies in HTTP - Miran al Mehrab
Overview of Cookies in HTTP - Miran al Mehrab
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
 
Optimising Web Application Frontend
Optimising Web Application FrontendOptimising Web Application Frontend
Optimising Web Application Frontend
 
Ch4(saving state with cookies and query strings)
Ch4(saving state with cookies and query strings)Ch4(saving state with cookies and query strings)
Ch4(saving state with cookies and query strings)
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
ASP.Net Presentation Part3
ASP.Net Presentation Part3ASP.Net Presentation Part3
ASP.Net Presentation Part3
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
Session,cookies
Session,cookiesSession,cookies
Session,cookies
 
Session and cookies,get and post
Session and cookies,get and postSession and cookies,get and post
Session and cookies,get and post
 
07 cookies
07 cookies07 cookies
07 cookies
 

Dernier

electrical installation and maintenance.
electrical installation and maintenance.electrical installation and maintenance.
electrical installation and maintenance.
benjamincojr
 
Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..
MaherOthman7
 
1893-part-1-2016 for Earthquake load design
1893-part-1-2016 for Earthquake load design1893-part-1-2016 for Earthquake load design
1893-part-1-2016 for Earthquake load design
AshishSingh1301
 

Dernier (20)

Worksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptxWorksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptx
 
electrical installation and maintenance.
electrical installation and maintenance.electrical installation and maintenance.
electrical installation and maintenance.
 
The Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxThe Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptx
 
Diploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfDiploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdf
 
5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...
 
Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...
Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...
Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...
 
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfInstruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
 
Piping and instrumentation diagram p.pdf
Piping and instrumentation diagram p.pdfPiping and instrumentation diagram p.pdf
Piping and instrumentation diagram p.pdf
 
Developing a smart system for infant incubators using the internet of things ...
Developing a smart system for infant incubators using the internet of things ...Developing a smart system for infant incubators using the internet of things ...
Developing a smart system for infant incubators using the internet of things ...
 
Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
 
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdflitvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
 
The battle for RAG, explore the pros and cons of using KnowledgeGraphs and Ve...
The battle for RAG, explore the pros and cons of using KnowledgeGraphs and Ve...The battle for RAG, explore the pros and cons of using KnowledgeGraphs and Ve...
The battle for RAG, explore the pros and cons of using KnowledgeGraphs and Ve...
 
Operating System chapter 9 (Virtual Memory)
Operating System chapter 9 (Virtual Memory)Operating System chapter 9 (Virtual Memory)
Operating System chapter 9 (Virtual Memory)
 
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
 
Raashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashid final report on Embedded Systems
Raashid final report on Embedded Systems
 
Linux Systems Programming: Semaphores, Shared Memory, and Message Queues
Linux Systems Programming: Semaphores, Shared Memory, and Message QueuesLinux Systems Programming: Semaphores, Shared Memory, and Message Queues
Linux Systems Programming: Semaphores, Shared Memory, and Message Queues
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptx
 
1893-part-1-2016 for Earthquake load design
1893-part-1-2016 for Earthquake load design1893-part-1-2016 for Earthquake load design
1893-part-1-2016 for Earthquake load design
 
Interfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfInterfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdf
 

19_JavaScript - Storage_Cookies_students.pptx

  • 1. Syllabus Introduction: Web Development and Client Side Programming, Protocols Governing Web, Internet Services and Tools, Client-Server Computing; HTML: Basic Syntax, Standard HTML Document Structure, Basic Text Markup, Images, Hypertext Links, Lists, Tables, Forms, HTML5; CSS: Creating Style Sheets, Levels of Style Sheets, CSS Properties, Style Specification Formats, Selector Forms, The Box Model, Conflict Resolution; Javascript: Basics of Javascript, Variables, Arrays and Operators, Functions, Event Handlers, Built-in JS Objects, Form Validations, Conditional and Loops, Storage and Cookies,Debugging and Testing; Introduction to AJAX: AJAX and Node.Js Server, The Xmlhttprequest Object, Handling The Response, Jquery, Passing Data, AJAX Application; PHP Programming: Introduction to PHP, Creating PHP Script, Running PHP Script, Variables and Constants, Data Types, Operators, Conditional Statements, Control Statements, Arrays, Functions, Working With Forms and Databases Connection, Introduction to Web-Server and XAMPP. 1
  • 2. Contents • Introduction • localStorage • sessionStorage • Cookies 2
  • 3. Introduction Data storage is crucial for creating dynamic, responsive, and personalized user experiences common methods to store data •localStorage •sessionStorage •Cookies
  • 4. localStorage • localStorage is part of the Web Storage API • provides a way to store data locally within the user's browser • Data stored using localStorage is persistent across browser sessions, i.e no expiration time • localStorage data for a document loaded in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed. • keys and the values stored with localStorage are always in the UTF-16 string format (two bytes per character) • Integer keys are always converted to strings localStorage.setItem(“myName”, “John”); const name = localStorage.getItem(“myName”); localStorage.removeItem(“myName"); localStorage.clear();
  • 5. sessionStorage • sessionStorage is similar to localStorage but with shorter lifecycle • A session is created with each page opened in a tab • Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window • Duplicating a tab copies the tab's sessionStorage into the new tab • page session lasts as long as the tab or the browser is open, and survives over page reloads and restores • data stored in sessionStorage is cleared when the page session ends (i.e., when the browser tab is closed). • sessionStorage creates different objects for different protocols (HTTP, HTTPS, FTP etc..) // Save data to sessionStorage sessionStorage.setItem("key", "value"); // Get saved data from sessionStorage let data = sessionStorage.getItem("key"); // Remove saved data from sessionStorage sessionStorage.removeItem("key"); // Remove all saved data from sessionStorage sessionStorage.clear();
  • 6. sessionStorage // Get the text field that we're going to track let field = document.getElementById("field"); // See if we have an autosave value // (this will only happen if the page is accidentally refreshed) if (sessionStorage.getItem("autosave")) { // Restore the contents of the text field field.value = sessionStorage.getItem("autosave"); } // Listen for changes in the text field field.addEventListener("change", () => { // And save the results into the session storage object sessionStorage.setItem("autosave", field.value); });
  • 7. Cookies • An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser. • Browser stores the cookie and sends it back to the same server with later requests • Useful in identifying if two requests come from the same browser—keeping a user logged in • remembers stateful information for the stateless HTTP protocol • Purposes of Cookies ◦ Session management: Logins, shopping carts, game scores, or anything else the server should remember ◦ Personalization: User preferences, themes, and other settings ◦ Tracking: Recording and analyzing user behavior
  • 8. Cookies • Client sends a HTTP request • Server responds with one or more set-cookie headers data and n HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser. • browser stores the cookie and sends it with requests made to the same server inside a Cookie HTTP header
  • 9. Cookies Cookies can have expiration time Set-cookie header format Set-Cookie: <cookie-name>=<cookie-value> Ex: Server sending 2 cookies HTTP/2.0 200 OK Content-Type: text/html Set-Cookie: yummy_cookie=choco Set-Cookie: tasty_cookie=strawberry Client sending cookies to server with a request GET /sample_page.html HTTP/2.0 Host: www.example.org Cookie: yummy_cookie=choco; tasty_cookie=strawberry
  • 10. Cookies: Lifetime Permanent cookies: are deleted at a date specified by the Expires (GMT String format) attribute or after a period prescribed by the Max-Age (number of seconds) attribute. If both Expires and Max-Age are set, Max-Age has precedence. Session cookies – cookies without a Max-age or Expires attribute Session cookies are deleted when the current session ends. The browser defines when the "current session" ends some browsers use session restoring when restarting. Set-Cookie: id=a3fWa; Expires=Thu, 31 Oct 2021 07:28:00 GMT; Set-Cookie: id=a3fWa; Max-Age=2592000
  • 11. Cookies: Secure and HttpOnly A cookie with the Secure attribute is only sent to the server with an encrypted request over the HTTPS protocol Secure cookies are never sent with unsecured HTTP (except on localhost). Anyone with access to the client's hard disk or JavaScript can read and modify the cookies To prevent access to cookies fro JavaScript, HttpOnly attribute is used Set-Cookie: id=a3fWa; Expires=Thu, 21 Oct 2021 07:28:00 GMT; Secure; HttpOnly
  • 12. Cookies: Domain and Path attributes • The Domain attribute of a cookie specifies which server can receive that cookie. ◦ Presence of Domain attribute: cookies are available on main domain and its subdomains. Ex: Domain=mozilla.org, cookies are available on mozilla.org and its subdomains like developer.mozilla.org ◦ Absence of Domain Attribute: cookies are available only on main domain • Invalid domain must be rejected by the browser ◦ Ex: following cookie sent by originalcompany.com must be rejected ◦ Set-Cookie: qwerty=219ffwef9w0f; Domain=somecompany.co.uk • The Path attribute indicates a URL path that must exist in the requested URL in order to send the Cookie. ◦ The %x2F ("/") character is considered a directory separator, ◦ Ex: Path=/docs, the matching request paths are ◦ /docs /docs/ /docs/Web/ /docs/Web/HTTP
  • 13. Cookies: Domain and Path attributes • The Path attribute indicates a URL path that must exist in the requested URL in order to send the Cookie. • If the Path attribute is not set, its default value is computed from the path of the URI that set the cookie ◦ If the path is empty, does not start with "/", or contains no more than one "/" character, then the default value for Path is "/". ◦ Ex: https://example.org or https://example.org/ the path is “/” ◦ Otherwise, the default value for Path is the path from the start up to but not including the final "/" character ◦ Ex: https://example.org/a/b/c, Path would be "/a/b"
  • 14. Cookies: SameSite attribute • A site is defined by a registered domain name and a scheme (http or https) ◦ Ex: https://jaipur.manipal.edu/ • The SameSite attribute lets servers specify whether/when cookies are sent with cross-site requests. • Three values are set for the SameSite attribute ◦ Strict: browser only sends the cookie with requests from the cookie's origin site ◦ Ex: Cookies from https://jaipur.manipal.edu/ are sent only to https://jaipur.manipal.edu/ ◦ Lax: Similar to Strict but user can reach origin page by navigation (or redirection) ◦ Doesn’t work with cross-site requests (Ex: accessing images or resources) ◦ Ex: Navigation to https://jaipur.manipal.edu/ via Google search ◦ manipal.edu home page requesting an image from https://images.google.com/ is a cross-site request ◦ None: Cookies are sent on both originating and cross-site requests, but only in secure contexts ◦ if SameSite=None then the Secure attribute must also be set • If no SameSite attribute is set, the cookie is treated as Lax (default value) Set-Cookie: mykey=myvalue; SameSite=Strict
  • 15. Cookies: SameSite attribute Set-Cookie: <cookie-name>=<cookie-value> Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value> Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date> Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<number> Set-Cookie: <cookie-name>=<cookie-value>; Partitioned Set-Cookie: <cookie-name>=<cookie-value>; Path=<path-value> Set-Cookie: <cookie-name>=<cookie-value>; Secure Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Strict Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Lax Set-Cookie: <cookie-name>=<cookie-value>; SameSite=None; Secure // Multiple attributes are also possible, for example: Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly
  • 16. Cookies: Creation document.cookie = "yummy_cookie=choco"; document.cookie = "tasty_cookie=strawberry"; console.log(document.cookie); // logs "yummy_cookie=choco; tasty_cookie=strawberry" Cookies created via JavaScript can't include the HttpOnly flag Cookies available to JavaScript can be stolen through XSS HttpOnly attribute prevents XSS attacks Cookies used for sensitive information (such as authentication) should have a short lifetime, with the SameSite attribute set to Strict or Lax
  • 17. Cookies Read all cookies accessible from current session allCookies = document.cookie; document.cookie returns a string containing a semicolon-separated list of all cookies (i.e. key=value pairs) document.cookie = "name=oeschger; SameSite=None; Secure"; document.cookie = "favorite_food=tripe; SameSite=None; Secure"; function showCookies() { const output = document.getElementById("cookies"); output.textContent = `> ${document.cookie}`; } function clearOutputCookies() { const output = document.getElementById("cookies"); output.textContent = ""; }
  • 18. Cookies document.cookie = "test1=Hello; SameSite=None; Secure"; document.cookie = "test2=World; SameSite=None; Secure"; const cookieValue = document.cookie.split("; ").find((row) => row.startsWith("test2="))?.split("=")[1]; function showCookieValue() { const output = document.getElementById("cookie-value"); output.textContent = `> ${cookieValue}`; } function clearOutputCookieValue() { const output = document.getElementById("cookie-value"); output.textContent = ""; }
  • 19. Cookies Writing/Updating a Cookie document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/"; cookie attribute values optionally follow the key-value pair, each preceded by a semicolon separator. Reading a Cookie const cookies = document.cookie.split('; '); const usernameCookie = cookies.find(cookie => cookie.startsWith('username=')); const username = usernameCookie.split('=')[1]; Deleting Cookie • You can delete a cookie by updating its expiration time to past date or max-age to zero or negative value