Search code examples
c#asp.netasp.net-mvc-5subdomainforms-authentication

Asp.Net Forms Authentication with Subdomains


I am running a single asp.net 4.5.2 application using mvc 5. I have custom routines made to handle subdomains for each Area of the application.

I have my user auth within one of the Areas (Profile), which is it's own subdomain. In the navigation bar, there is a login form that POSTs to the Login() action of the Profile controller. Since this is a subdomain, I am setting the domain info for the auth manually to have it work across all subdomains.

For the life of me, I cannot figure out how to get it to work. I've tried setting the Form Auth domain to the TLD, the TLD with a . in front, with the forms info in webconfig, and without.

Here are the important bits concerning forms auth:

Web.Config

<system.web>
  <authentication mode="Forms">
  <forms domain=".teknik.io" protection="All" enableCrossAppRedirects="true" name="TeknikAuth" />
  </authentication>
</system.web>

<system.webServer>
  <modules>
    <remove name="FormsAuthentication" />
    <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
  </modules>
</system.webServer>

Profile Controller

public ActionResult Login(LoginViewModel model)
{
  ...

  authcookie.Name = "TeknikAuth";
  authcookie.HttpOnly = true;
  authcookie.Secure = true;
  authcookie.Domain = string.Format(".{0}", Config.Host); // ".teknik.io"
  Response.Cookies.Add(authcookie);

  ...
}

Update 1

I have determined that it is working on my dev domain (single domain), and when I then visit the main domain, the cookie is still working. The only difference between the two is that on dev, the login request is on the same subdomain, while on production, it is sending the request to another subdomain.


Solution

  • So I figured out what was wrong. When logging in (and setting the cookie), I was sending a post request to a different domain than the one I was currently on (profile.teknik.io/Login). This for some reason was not setting the proper cookie, so no auth was occurring. Once I moved the login to the parent domain, the auth works correctly across subdomains.

    Update 1

    The real issue was the ajax request for logging in. It did not have CORS enabled, so once I did that, and added the appropriate allow headers, the request would work and the cookies would be saved correctly.