1

I am setting a cookie via document.cookie = 'foo=bar;secure;path=/;' and I'm connecting to a WebSocket. I have tried the samesite=None and many other variations with none being successful, so I'm somewhat stuck. I want to use this cookie for authentication (it's actually a jwt and a specific api key in pair).

The flow is:

  • Open front-end app
  • Login, get jwt back
  • Store JWT and Special API key in token
  • Make a websocket request
  • If made with cookie - everything works

This works locally when both the front-end application and back-end application are on localhost.

The cookie is magically not being sent by the front-end application when in production when both apps are deployed. They're both hosted on heroku and are being pointed to subdomains x.mysite.com and y.mysite.com respectively.

Is there a specific browser behaviour that I need to be aware of?

Thanks in advance.

Borko Kovacev
  • 890
  • 2
  • 10
  • 29

1 Answers1

1

Due to CSRF attacks, browsers do not allow access to cookies from one domain to an application on another domain. Even subdomains of the same domain are not allowed by default. To enable cookies shared across domains, you have to specify it as described in this answer. That means that if you want mysite.com, x.mysite.com, y.mysite.com to access the same cookie, you have to set your cookie this way:

Set-Cookie: name=value; domain=mysite.com

In Django, you can achieve this using the SESSION_COOKIE_DOMAIN setting. So in your settings file, you can have:

SESSION_COOKIE_DOMAIN = os.environ.get('SESSION_COOKIE_DOMAIN', 'mysite.com')
Ken4scholars
  • 4,794
  • 2
  • 13
  • 28