I've got two DBs, one for business entities and one for Identity. I'm also using external (Azure Ad) login to authenticate to Identity. All of this worked when I had it all in one DB and one DbContext. However, as soon as I split it out, the issue I run into is that after logging in, on subsequent requests User.Identity.IsAuthenticated is false (and thus User.Identity.Name is null, as well as Role/Claims data... you get the point). No errors are thrown anywhere in the external registration/login process; it's just as if my application does not know which context to look at for User.Identity information.
Here is the body of my ConfigureServices in Startup.cs:
services.AddAuthentication(sharedOpts =>
{
sharedOpts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOpts.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAd(opts => Configuration.Bind("AzureAd", opts))
.AddCookie();
services.AddIdentity<AspNetUsers, AspNetRoles>()
.AddEntityFrameworkStores<CoreUMContext>()
.AddDefaultTokenProviders();
services.AddMvc();
string dataConnection = Configuration["ConnectionStrings:TrackerDatabase"];
string userConnection = Configuration["ConnectionStrings:UserDatabase"];
Trace.TraceWarning("Connecting to connection at: " + dataConnection);
try {
services.AddDbContext<EdgeContext>(options => options.UseSqlServer(dataConnection));
services.AddDbContext<CoreUMContext>(options => options.UseSqlServer(userConnection));
}
catch (Exception ex) {
Trace.TraceError("Error connecting to DB: " + ex);
}
I know middleware can be tricky with the order you add to the pipeline, so I've tried every combo (.AddIdentity before .AddAuthentication, adding CoreUMContext before the EdgeContext, etc.). Injecting the Identity context (CoreUMContext) into my controllers does not solve the issue either.
Again, this line works
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
and result.Succeeded returns true, so to some degree it's working, but I can't seem to find good literature on the exact path User.Identity follows to resolve itself.
I'd greatly appreciate if anyone can shed light, as I'd really like to not have to go back to an all-in-one-db or all-in-one-context scenario as this doesn't really fit my architectural requirements.
UPDATE
It seems that the issue is Chrome not storing/sending the property cookie Identity uses to resolve which user is making the request. It works in Microsoft Edge however. This switched at some point for me yesterday and I'm still trying to deduce why (clearing cookies has not worked), but it appears the multiple contexts were not the cause of the problem.