简体   繁体   中英

Setting a cookie from a remote domain for local development

So I am trying to set up environment for local development to pull data from my dev server at dev.mydomain.com .

The tornado REST server serving data uses a cookie-based authentication.

To obtain the cookie I sent an AJAX post login request to the server (from the website at localhost ), and the secure cookie comes back in a response. I can see that in the chrome console (network->cookies). It has the proper name, value, domain ( dev.mydomain.com ) and everything.

Yet, the cookie doesn't get set and the REST requests that follow fail. It is not cross-origin related. If I go to dev.mydomain.com and log in manually in another tab the cookie gets set correctly and all my subsequent requests sent from local domain work fine (since they grab the now-existent cookie).

All my requests contain this:

xhrFields: {
  'withCredentials': true
}

And this is how my tornado server sets the cookie:

self.set_secure_cookie(
  COOKIE_NAME, tornado.escape.url_escape(str(COOKIE_VALUE)),
  expires_days=1, domain="dev.mydomain.com"
)

Any idea why the cookie doesn't get set if the login request comes from localhost ?

I tried mapping 127.0.0.1 to foo.mydomain.com (for whatever that's worth) but this doesn't help.

Also, I cannot grab the cookie with javascript. Tried xhr.getResponseHeader('Set-Cookie'); , yields null.

Somehow it makes sense to me that if you set the cookie for dev.mydomain.com that it does neither work for foo.mydomain.com nor for localhost .

What happens if you do something like this:

self.set_secure_cookie(
  COOKIE_NAME, tornado.escape.url_escape(str(COOKIE_VALUE)),
  expires_days=1, domain=".mydomain.com"
)

*.mydomain.com might work then.

EDIT:

Actually, I checked over and over again, and I can't find an example where people used the argument 'domain' for set_secure_cookie() but instead this argument exists for 'set_cookie()', as stated in the docs :

Additional keyword arguments are set on the Cookie.Morsel directly. See http://docs.python.org/library/cookie.html#morsel-objects for available attributes.

If you are sure about using secure cookies, you should first get sure to use a cookie secret in your application settings

class Main(web.Application):
    def __init__(self):
        settings = dict(
            cookie_secret = "xxxx",
        )

then try to set the secure cookie, without specifying the domain

self.set_secure_cookie(
  COOKIE_NAME, tornado.escape.url_escape(str(COOKIE_VALUE)),
  expires_days=1
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM