Search code examples
ajaxcookiesauthenticationtornado

Tornado: how to send back cookies with ajax


I'm using Tornado to build a web server and Now I'm coding the login module: after doing login, user can send a message to the server.

My idea is as below:
When the user login successfully, the server will set a secure cookie: self.set_secure_cookie("user", username, expires=time.time() + 60).

Then when the user sends a message to the server, the request should contain the cookie that the server just set to tell the server the identity of the user. If there is no cookie in the request, the server will redirect to the login page.

Now the problem is: the server can't get any cookie.

Login:
enter image description here

You can see that a cookie is set when user does login.

Then the browser tries to send a message to the server with ajax:

url: 'http://www.example.com/addcomment',
method: post,
crossDomain: true,
data: message,
processData: false,
cache: false

However, when the server tried to self.get_secure_cookie("user"), it gets a None, which means that the request doesn't send any cookie to the server.

I also add

xhrFields: {
    withCredentials: true
},

to the ajax but it doesn't work either.

If ajax can't send any cookie to the server, how could I use the secure cookies of Tornado?


Solution

  • well,after set cookie you can redirect to visit_page_url

    self.set_secure_cookie
    self.redirect(visit_page_url)
    

    if you via chrome check redirect network request headers,you will find like this have Cookie field: enter image description here