Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to different domain with a cookie in Express js

I'm developing a web app using Express on Node. I'm trying to implement a proxy login functionality where an user is directly logged in and redirected to another site after he logs into to my site.

In my routing function I'm writing the following code
res.cookie('fanws', 'value' );
res.redirect('http://hostname/path');
// another site

I used the debugger in chrome and saw that the cookie is not getting added in the redirected page.

I'm running the app on localhost and the site which i'm redirecting to is hosted on another server on local network.

What should I do to add the cookie on the redirected path?

like image 433
Kiran G Avatar asked Aug 10 '15 00:08

Kiran G


1 Answers

In a nutshell, you can't set a cookie in a browser or read a cookie for a site that you do not control the server for or have your own client code in that page. The cookie system is designed that way on purpose for security reasons. So, from a page or server for http://www.domain1.com, you cannot read or set cookies for some other domain.

If you have code in the pages of both domains, then you can pass some info to the second page (most likely as a query parameter) that tells the code in the redirected page to take some action (like set a cookie), but you must control the Javascript or server in that second page in order to be able to do that.


The cookie in your nodejs code goes on the current request/response which means it is associated with that domain in the browser when the response from the current request is processed by the browser.

res.redirect(...) returns a 302 response with a new URL as the response to the current request. The browser then sees this response code and makes a new web request to the new page. You cannot set cookies from the server for that new domain unless you have the server for that domain also. This is a fundamental aspect of cookie security. Cookies can only be accessed via Javascript in the browser from the page in the same origin as the cookie belongs and servers can only set cookies for the particular origin in the particular request that they are processing.

like image 63
jfriend00 Avatar answered Oct 28 '22 14:10

jfriend00