为什么context.Request.Context.Authentication.SignIn没有生成cookie?

时间:2015-11-16 20:53:02

标签: asp.net cookies asp.net-web-api oauth owin

我们有一个MVC 5应用程序,我们已经添加了Web Api控制器以提供REST API功能。我们已使用自定义OAuth提供程序类通过OWIN管道成功实施了OAuth身份验证。

现在我们要实现身份验证cookie以保护服务器上的静态资源。我确信还有其他百万种方法可以做到这一点,但是对资源的请求是直接链接到该资源的链接,所以我不能使用我的OAuth令牌或任何其他机制,这就是我们想要使用cookie的原因......浏览器已经发送它们,无需更改任何内容。

从我读过的所有内容中,可以使用OWIN管道进行承载令牌认证和Cookie认证。基本上,Web API将使用Bearer Tokens,因为所有客户端都将提供,并且对服务器上某些静态资源的请求将使用在所有请求上发送的Cookie。

我们的问题是,使用下面的代码永远不会生成auth cookie。在整个管道中,我从未在响应中看到 set-cookie 标头,这就是我将Kentor Cookie Saver添加到管道中的原因......它应该有所帮助。

WebApiConfig.cs

...
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
...

Startup.Auth.cs

...
app.UseOAuthBearerTokens(OAuthOptions);
// I was told this might help with my cookie problem...something to do with System.Web stripping Set-Cookie headers
app.UseKentorOwinCookieSaver();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
  AuthenticationType = Microsoft.Owin.Security.Cookies.CookieAuthenticationDefaults.AuthenticationType,
  AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
  ExpireTimeSpan = TimeSpan.FromHours(4)
});
...

自定义OAuth提供程序

...
// Creates our claims and properties...keep in mind that token based authentication is working
CreatePropertiesAndClaims(acct, out properties, out claims);
if (IsAccountAuthorized(claims))
{
  AuthenticationProperties authProps = new AuthenticationProperties(properties);
  ClaimsIdentity claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
  claimsIdentity.AddClaims(claims);

  AuthenticationTicket ticket = new AuthenticationTicket(claimsIdentity, authProps);
  context.Validated(ticket);

  ClaimsIdentity cookieIdentity = new ClaimsIdentity(claims, Microsoft.Owin.Security.Cookies.CookieAuthenticationDefaults.AuthenticationType);
  context.Request.Context.Authentication.SignIn(cookieIdentity);    // This should create the auth cookie!??!
}
else
{
  context.SetError("Unauthorized", "You don't currently have authorization. Please contact support.");
}
...

请记住,基于令牌的身份验证正在运行,因此我假设配置设置丢失或配置错误,或者是管道排序问题。

谢谢!

1 个答案:

答案 0 :(得分:0)

我知道这是一个迟到的答案,但我们遇到了完全相同的问题。我的同事和我花了4个小时试图找出原因。这是一个答案,希望可以拯救别人从头撞墙。

检查响应,你可以看到有Set-Cookie:.AspNet.Cookies=LqP1uH-3UZE-ySj4aUAyGa8gt ....但是没有保存的cookie。您需要做的是,在您的ajax调用中,包括凭据。

$.ajax({
    url: url,
    type: 'POST',
    xhrFields: {
        withCredentials: true
    }
)

我们正在使用Fetch API,它看起来像以下

fetch(url, {  
  method: 'post',  
  headers: {  
    "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"  
  }, 
  credentials: 'include'  
})