Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Subdomain Cookie (parent and one subdomain)

I have an app with multiple subdomains, subone.parent.com, subtwo.parent.com.

I have a logon page at parent.com/login. When a user logs in I redirect them to the proper domain based on which one they are a member of. This works fine.

FormsAuthenticationTicket ticket = new FormsAuth...
string encTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
cookie.Domain = subone.parent.com
Response.Cookies.Add(cookie)

This properly authenticates the user for subone.parent.com and not subtwo.parent.com. However I would like to do the following.

If the user goes back to parent.com, I would like to know that they are logged in and redirect them back to subone.parent.com.

Is there a best practice for accomplishing this? Or do I have to set another cookie for parent.com?

I'm working in asp.net mvc if it matters.

THanks!

like image 206
Paul Avatar asked Jan 31 '10 16:01

Paul


People also ask

Can two subdomains share cookies?

To share cookies across subdomains, you can simply create cookies with the domain directive set to the parent domain, in this case, example.com, rather than either of the specific subdomains. In my browser, I have the index and product detail pages open.

Can subdomain access parent domain cookies?

If a cookie is scoped to a parent domain, then that cookie will be accessible by the parent domain and also by any other subdomains of the parent domain.

Can subdomain set cookie for another subdomain?

example.com (with the leading dot) in the cookie that all subdomains can share a cookie. Can subdomain.example.com access a cookie created in example.com (without the www subdomain)? Can example.com (without the www subdomain) access the cookie if created in subdomain.example.com ? Yes you can..

Can you have 2 subdomains?

You create subdomains to help organize and navigate to different sections of your main website. Within your main domain, you can have as many subdomains as necessary to get to all of the different pages of your website.


1 Answers

You can share cookies across domains like you are trying to do, but its not straight forward, example here.

Another options is to set the cookie to be ".parent.com" rather than specifying the sub-domain explicitly and use the cookie store the details of the sub-domain. Then you can access the cookie from any of your sub-domains (and parent assuming its www.parent.com).

If your using MVC, you can pretty easily create a custom filter and add to the www.parent.com controllers to check for the existence of the cookie, and if so redirect to the sub domain the cookie specifies. Further details of filters here.

like image 187
Rosstified Avatar answered Sep 29 '22 23:09

Rosstified