I have an OWIN Self-hosted Web Api and some MVC web applications all in the same domain. Web applications are calling the Web Api in server side. They use OWIN cookie authentication like this:
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext<MyUserManager>(MyUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity =
SecurityStampValidator.OnValidateIdentity<MyUserManager, MyUser, Guid>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: (manager, user) =>
user.GenerateUserIdentityAsync(manager),
getUserIdCallback: (id) => (new Guid(id.GetUserId())))
}
});
}
Being in the same domain, when user sign in one web application, the cookies are available in other web applications and the user is signed in.
I implement cookie authentication in my self-hosted web api like this:
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.MessageHandlers.AddRange(new List<DelegatingHandler>
{
new ServerContextInitializerHandler(), new LogRequestAndResponseHandler(),
});
config.MessageHandlers.AddRange(ServiceLocator.Current.GetAllInstances<DelegatingHandler>());
config.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
Provider = new CookieAuthenticationProvider(),
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
});
appBuilder.UseWebApi(config);
}
I expect to have the user in web api, as it's in the same domain and the cookies are all available in received requests. The problem is the Request.GetRequestContext().Principal is null (and other alternatives like Request.GetOwinContext().Authentication.User).
I emphasis that the Request.GetOwinContext().Request.Cookies contains all cookies that are available in the web application.