Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I see cookie value in a WebSocket handshake request header?

I wanted to send a websocket handshake request from an html page and wrote codes like below:

  document.cookie = "guestId=xxxx; remember=xxxxxx;";
  var ws = new WebSocket("ws://localhost:5000/ws");

But what shown in Chrome Dev Tools appears that no cookie was sent:

General:
  Request URL:ws://localhost:5000/ws
  Request Method:GET
  Status Code:307 Temporary Redirect
Response Headers
  Content-Length:59
  Content-Type:text/html; charset=utf-8
  Date:Fri, 18 Mar 2016 09:39:11 GMT
  Location:/preorder/landing/index
Request Headers
  Accept-Encoding:gzip, deflate, sdch
  Accept-Language:en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4
  Cache-Control:no-cache
  Connection:Upgrade
  Host:localhost:5000
  Origin:http://localhost:63342
  Pragma:no-cache
  Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits
  Sec-WebSocket-Key:t3N0vVaLCsOmOXLSh+Arsw==
  Sec-WebSocket-Version:13
  Upgrade:websocket
  User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36

How can I fix this? Why there is no cookie in request headers? If I send other ajax request not upgraded, I can see cookies in Dev Tools. Why is there such differences?

like image 490
Yan Yang Avatar asked Mar 18 '16 10:03

Yan Yang


People also ask

How do I send a cookie from a WebSocket?

Although, in theory, one could use cookies, as all WebSocket connections start with an HTTP request (with an upgrade header on it), and the cookies for the domain you are connecting to, will be sent with that initial HTTP request to open the WebSocket.

What is the difference between a cookie and a header?

HTTP headers are used to pass additional information with HTTP response or HTTP requests. A cookie is an HTTP request header i.e. used in the requests sent by the user to the server. It contains the cookies previously sent by the server using set-cookies. It is an optional header.

How do I send cookies from server to client?

The Set-Cookie HTTP response header is used to send a cookie from the server to the user agent, so that the user agent can send it back to the server later. To send multiple cookies, multiple Set-Cookie headers should be sent in the same response.


1 Answers

Your Origin header is http://localhost:63342 and the WS request is to ws://localhost:5000/ws so your domains are different (different ports). I imagine your other ajax requests are to http://localhost:63342 and thus the browser sends the cookie.

like image 167
Michael Avatar answered Oct 27 '22 16:10

Michael