【发布时间】:2015-08-05 14:59:28
【问题描述】:
我有一个 OWIN 自托管 Web Api 和一些 MVC Web 应用程序都在同一个域中。 Web 应用程序在服务器端调用 Web Api。他们像这样使用 OWIN cookie 身份验证:
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())))
}
});
}
在同一个域中,当用户登录一个 web 应用程序时,cookie 在其他 web 应用程序中可用并且用户已登录。
我在我的自托管 web api 中实现 cookie 身份验证,如下所示:
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);
}
我希望用户在 web api 中,因为它在同一个域中,并且 cookie 在收到的请求中都可用。 问题是 Request.GetRequestContext().Principal 为空(以及其他替代方案,如 Request.GetOwinContext().Authentication.User)。
我强调 Request.GetOwinContext().Request.Cookies 包含 Web 应用程序中可用的所有 cookie。
【问题讨论】:
标签: authentication cookies asp.net-web-api owin self-hosting