自托管Web Api中的OWIN Cookie身份验证

时间:2015-03-07 11:40:39

标签: authentication cookies asp.net-web-api owin self-hosting

我有一个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应用程序中可用,并且用户已登录。

我在我自己托管的网络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为null(以及其他替代方法,如Request.GetOwinContext()。Authentication.User)。

我强调Request.GetOwinContext()。Request.Cookies包含Web应用程序中可用的所有cookie。

1 个答案:

答案 0 :(得分:4)

提出这个问题已经过了很长时间,但目前还没有答案,但我找到了原因并且我只是分享它。希望有用。 正如我所提到的,我在自我托管的web api中实现了cookie身份验证,并且在web api中收到的请求中提供了身份验证cookie。 问题是,在Web应用程序(用户登录的位置)中,OWIN中间件将ClaimsIdentity数据编码为访问令牌并将其放入身份验证cookie中,并访问此cookie中的身份验证数据,对其进行解码&#39;的内容。 Web应用程序的这种编码和解码是通过使用运行服务器的计算机的机器密钥进行加密和解密,以及使用另一种名为DPAPI的方式在自托管的Web api中完成的。 所以,我在web api请求上有了身份验证cookie,但由于OWIN中间件试图使用DPAPI进行解密,因此无法从cookie中提取访问令牌。

相关问题