CORS & WEBSOCKETS Dealin g wit h Sam e -Origi n Polic y - - PowerPoint PPT Presentation

cors websockets dealin g wit h sam e origi n polic y
SMART_READER_LITE
LIVE PREVIEW

CORS & WEBSOCKETS Dealin g wit h Sam e -Origi n Polic y - - PowerPoint PPT Presentation

CS 498RK SPRING 2020 CORS & WEBSOCKETS Dealin g wit h Sam e -Origi n Polic y application lives on llama.com and you want to pull data from www.alpaca.com var xhr = new XMLHttpRequest(); xhr.open('GET',


slide-1
SLIDE 1

SPRING 2020 CS 498RK

CORS &
 WEBSOCKETS

slide-2
SLIDE 2

Dealing with 
 Same-Origin Policy

slide-3
SLIDE 3

application lives on llama.com and you want to pull data from www.alpaca.com

What happens?

var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://www.alpaca.com/hello.json'); xhr.onload = function(e) { var data = JSON.parse(this.response); ... } xhr.send();

slide-4
SLIDE 4

application lives on llama.com and you want to pull data from www.alpaca.com

  • rigin mismatch error!

var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://www.alpaca.com/hello.json'); xhr.onload = function(e) { var data = JSON.parse(this.response); ... } xhr.send();

slide-5
SLIDE 5

SAME-ORIGIN POLICY

implemented by all major browsers

  • nly web pages that have the same “origin” can access

each other’s data

  • rigin = protocol, domain name, port (some browsers)

does not apply to <img> and <script>

slide-6
SLIDE 6

SAME-ORIGIN POLICY

… but applies to AJAX requests "Cross-domain" AJAX requests are forbidden by default because of their ability to perform advanced requests POST, PUT, DELETE and other types of HTTP requests, along with specifying custom HTTP headers introduce many security issues as described in cross-site scripting

slide-7
SLIDE 7

CROSS-ORIGIN RESOURCE SHARING

CORS allows web applications on one domain to make cross domain AJAX requests to another domain. Access-Control-Allow-Origin header in HTTP responses more freedom than purely same-origin requests, but more secure than allowing all cross-origin requests

http://www.html5rocks.com/en/tutorials/file/xhr2/ html5 feature

slide-8
SLIDE 8

CORS WORKAROUND

// browser sends the following request header

Origin: http://llama.com

// server response: give access to llama.com

Access-Control-Allow-Origin: http://llama.com

// give access to all domains Access-Control-Allow-Origin: *

slide-9
SLIDE 9

Access-Control-Allow-Origin: *

useful when a page or API is intended to be accessible to everyone, including any code on any site freely-available web fonts — Google Fonts

slide-10
SLIDE 10

CORS IN ACTION

//Allow CORS so that backend and frontend could be put on different servers var allowCrossDomain = function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested- With, X-HTTP-Method-Override, Content-Type, Accept"); next(); }; app.use(allowCrossDomain);

slide-11
SLIDE 11

AJAX CALLS

If the server endpoint has enabled CORS, making the cross-origin request is no different than a normal XMLHttpRequest request

slide-12
SLIDE 12

JSONP

allows a page to receive JSON data from a different domain by adding a <script> element to the page which loads a JSON response with a callback from a different domain

“JSON with padding”

slide-13
SLIDE 13

function processJSON (json) { // Do something with the JSON response };

schock.net/articles/2013/02/05/how-jsonp-really-works-examples/

Create callback function

slide-14
SLIDE 14

<script> function processJSON (json) { // Do something with the JSON response }; </script> <script src='http://api.flickr.com/services/feeds/photos_public.gne? jsoncallback=processJSON&tags=monkey&tagmode=any&format=json'></script>

schock.net/articles/2013/02/05/how-jsonp-really-works-examples/

Dynamically inject <script> tag

slide-15
SLIDE 15

processJSON( { "title": "Recent Uploads tagged monkey", "link": "http://www.flickr.com/photos/tags/monkey/", "description": "", "modified": "2015-02-03T21:23:22Z", "generator": "http://www.flickr.com/", "items": [ // ... Much more JSON here ... ] } )

schock.net/articles/2013/02/05/how-jsonp-really-works-examples/

Server Response

slide-16
SLIDE 16

CORS VS JSONP

Use regular XMLHttpRequest with CORS JSONP only supports GET, CORS supports other types of HTTP requests JSONP can cause cross-site scripting (XSS) issues where the external site is compromised, CORS allows websites to manually parse responses to ensure security JSONP works on legacy browsers which predate CORS support

Use CORS unless you need to support older browser versions

slide-17
SLIDE 17

WebSockets

slide-18
SLIDE 18

MY BLOG

ADD POST This is my first post.

MY BLOG

NEW POST This is my first post. 02/23/15

API DATABASE

Client Server

HTTP POST HTTP GET

slide-19
SLIDE 19

MY BLOG

ADD POST This is my first post.

MY BLOG

NEW POST This is my first post. 02/23/15

API DATABASE

Client Server

HTTP POST HTTP GET

AJAX allows server requests to be made in the background

slide-20
SLIDE 20

…but if clients don’t request, servers can’t respond!

slide-21
SLIDE 21

What types of applications need servers to push data?

slide-22
SLIDE 22

LOW-LATENCY, REAL-TIME

Multiplayer online games Chat applications Realtime updating social streams

slide-23
SLIDE 23

How can servers push data?

slide-24
SLIDE 24

POLLING

keep making requests to the server to see if there’s any new information performance problems: server has to process HUGE number of connections a second

aka faking it

slide-25
SLIDE 25

COMET

a set of more advanced techniques hidden iframes (i.e., forever frames) AJAX with long polling unstandardized hacks, performance issues

not an acronym!

en.wikipedia.org/wiki/Comet_%28programming%29

slide-26
SLIDE 26

BROWSER PLUGINS

Adobe Flash, Java raw push real-time data to clients through raw TCP socket connections with servers plug-ins not guaranteed to be installed, firewall issues

slide-27
SLIDE 27

WebSockets

slide-28
SLIDE 28

WEBSOCKETS

WebSocket API introduced in HTML5 (2009) persistent connection between the client and server send data back and forth without HTTP overhead

en.wikipedia.org/wiki/WebSocket

bidirectional full-duplex communication

slide-29
SLIDE 29

GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 Origin: http://example.com

en.wikipedia.org/wiki/WebSocket

Client Request

slide-30
SLIDE 30

HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk= Sec-WebSocket-Protocol: chat

en.wikipedia.org/wiki/WebSocket

Server Response

slide-31
SLIDE 31

var connection = new WebSocket(‘ws:// html5rocks.websocket.org/echo'); Open a WebSocket Connection

www.html5rocks.com/en/tutorials/websockets/basics/

slide-32
SLIDE 32

// When the connection is open, send some data to the server connection.onopen = function () { connection.send(‘Lorenzo Llamas'); // Send the message ‘Lorenzo Llamas' to the server }; // Log messages from the server connection.onmessage = function (e) { console.log('Server: ' + e.data); }; // Log errors connection.onerror = function (error) {/*…*/}; // Close connection connection.onclose = function(){ /*…*/ }

www.html5rocks.com/en/tutorials/websockets/basics/

Atuach Event Handlers

slide-33
SLIDE 33

CROSS ORIGIN COMMUNICATION

supports communication between clients and servers on any domain server decides which domains to allow connections from

www.html5rocks.com/en/tutorials/websockets/basics/

slide-34
SLIDE 34

PROBLEMS

Immediate security concerns (Opera 11, Safari 5) Protocol was revamped and now supported by all modern browsers Incompatibility with HTTP upgrade system and some proxy servers

even if client supports it, can’t establish a connection!

slide-35
SLIDE 35

WEBSOCKETS TODAY

use libraries that use earlier fallbacks whenever WebSocket is not available socket.io

slide-36
SLIDE 36

Socket.IO

slide-37
SLIDE 37

If at first you don’t succeed…

WebSockets Adobe Flash Socket Ajax long polling Ajax multipart streaming Forever iFrame JSONP Polling

slide-38
SLIDE 38

“Socket.IO enables real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed.”

socket.io

slide-39
SLIDE 39

Demo

slide-40
SLIDE 40

<script> var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); </script>

socket.io

Client Code

slide-41
SLIDE 41

app.get('/', function(req, res){ res.sendfile('index.html'); }); io.on('connection', function(socket){ socket.on('chat message', function(msg){ io.emit('chat message', msg); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); });

socket.io

Server Code