We're using ASP.NET Identity but have make a very small extension to the cookie authenticator to enable sub-domain authentication i.e. we set the auth cookie to bear a hostname like.domain.com (note the preceding dot) instead of domain.com ormy.domain.com. We do it so the user is authenticated the domain and all subdomains hosted by that single ASP.NET MVC 5 app.
Problem
On the very FIRST attempt after app cold start, the cookie STILL bears the domainmy.domain.com (our logins are on my.domain.com) DESPITE setting it to.domain.com
after executing the SubdomainCookieAuthentication code below. We've confirmed that even on the 1st cold boot the code indeed sets the right domain in the cookie (stepped via breakpoints in code below) but the cookie that reaches the client doesnt have it. On 2nd and subsequent attempts, the cookie hostname logic works just fine.
Question
How can I fix this so it works even on the first attempt? The code below is super simple leading us to believe the bug might be within ASP.NET Identity itself but we couldn't find a way to alert the ASp.NET Identity team about this.
Code
Custom cookie auth
public class SubdomainCookieAuthentication : CookieAuthenticationProvider { public override void ResponseSignIn(CookieResponseSignInContext context) { // We need to add a "." in front of the domain name to // allow the cookie to be used on all sub-domains too var hostname = context.Request.Uri.Host; // works for www.google.com => .google.com // will FAIL for www.google.co.uk (gives .co.uk) but doesn't apply to us var dotTrimmedHostname = Regex.Replace(hostname, @"^.*(\.\S+\.\S+)", "$1"); context.Options.CookieDomain = dotTrimmedHostname; base.ResponseSignIn(context); } }
This is initialized inside the Owin startup class as follows
Class: Startup
File: App_start\Startup.Auth.cs
publicvoidConfigureAuth(IAppBuilder app){ app.UseCookieAuthentication(newCookieAuthenticationOptions{AuthenticationType=DefaultAuthenticationTypes.ApplicationCookie,LoginPath=newPathString("/Account/Login"),Provider=newSubdomainCookieAuthentication()});}