I've been trying to build a local proof of concept to move over our current solution to a different URL structure. I'm using ASP.NET with 3 projects that currently has these URLs mapped to them:
mysite.com
mysite.com/api
mysite.com/app
To setup the proof of concept I've setup 3 sites locally in IIS with the following URLs:
mysite.com
api.mysite.com
app.mysite.com
And have added the following entries into the HOSTS file:
127.0.0.1 mysite.com
127.0.0.1 app.mysite.com
127.0.0.1 api.mysite.com
Currently app.mysite.com
talks to api.mysite.com
to perform a user login, which returns a cookie back in the response. The issue is that the cookie is not being stored under mysite.com
. Subsequent requests to api.mysite.com
don't have the cookie attached in the request header, and therefore fail.
I've experimented setting the cookie's domain
property with no success, as well as not including a domain property.
An example of a cookie returned in the request:
Set-Cookie: MyCookie=somestuff; domain=.mysite.com; expires=Sat, 06-Sep-2014 00:02:04 GMT; path=/; HttpOnly
Yet the cookie is never attached to any requests to api.mysite.com
nor can i see it in the cookie browser of Chrome, Firefox, IE etc...
Note that I've enabled CORS in web.config to enable cross domain requests.
EDIT: In response to Owain's answer. I'll clarify my current setup a little more.
Regarding <machineKey>
I have created a machineKey and used the same values on both applications in the web.config
file. This was already working locally and in production when using mysite.com/api
and mysite.com/app
It wasn't till moving to subdomains that i ran into this issue.
Here is my code for creating and attaching the cookie:
private void EncryptAndAttachCookieToHeaders(FormsAuthenticationTicket ticket)
{
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie newCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
newCookie.Domain = ".mysite.com";
newCookie.Expires = DateTime.Now.AddMonths(3);
newCookie.HttpOnly = true;
newCookie.Secure = false;
System.Web.HttpContext.Current.Response.Cookies.Add(newCookie);
// For testing purposes
HttpCookie hc = new HttpCookie("cookie1", "value");
hc.Domain = ".mysite.com";
hc.Expires = DateTime.Now.AddMonths(3);
HttpContext.Current.Response.Cookies.Add(hc);
HttpCookie hd = new HttpCookie("cookie2", "value");
hd.Domain = ".api.mysite.com";
hd.Expires = DateTime.Now.AddMonths(3);
HttpContext.Current.Response.Cookies.Add(hd);
All of these cookies (real one plus the two tests) are visible when viewing the response in Fiddler. However subsequent requests to api.mysite.com
do NOT have any cookies attached in the request header. The browser doesn't seem to want to store the cookie now that I've moved to the subdomain structure.