I'm using Umbraco 7.5 with an OWIN startup class.
Despite the shortcomings with using cookie auth, I'm trying to share the cookie auth between both MVC and Web API.
I have this in my OWIN startup class:
private static void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
CookieSecureOption secureCookieOption = CookieSecureOption.SameAsRequest;
#if DEBUG
secureCookieOption = CookieSecureOption.Never;
#endif
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
AuthenticationMode = AuthenticationMode.Active,
LoginPath = new PathString("/Account/Login"),
CookieSecure = secureCookieOption,
CookieManager = new ChunkingCookieManager(),
Provider = new CookieAuthenticationProvider()
}, PipelineStage.Authenticate);
//configure B2C OAuth middleware
foreach (string policy in AppSettings.B2CPolicies)
{
app.UseOpenIdConnectAuthentication(CreateBearerOptionsFromPolicy(policy));
}
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
This works fine as far as the Umbraco & custom MVC pages are concerned - the current user identity is available and the Umbraco helper methods work as expected.
However for Web API controllers - whether derived from UmbracoApiController or just ApiController, the current user identity on the HTTP Context is always null. I have checked the browser request being sent for to the API controllers, and the ASPNET identity cookie is included, so I'm confused as to why this doesn't translate to a user identity on the thread & httpcontext. Anyone able to shed some light on that?
Edit: some more info on this- I tried creating my own custom cookie authentication middleware and replaced the standard MS CookieAuthenticationHandler with my custom implementation so that I could trace the calls through it. Interestingly, for a normal MVC page, the AuthenticateCoreAsync method is invoked as the page loads, which successfully reads the cookie and returns a valid authentication ticket. For the Web API call, the AuthenticateCoreAsync method is not invoked at all before the API method is hit.