2015-11-16 22 views
4

我們有一個MVC 5應用程序,我們添加了Web Api控制器以提供REST API功能。我們已經使用自定義OAuth提供程序類,通過OWIN管道成功實施了OAuth身份驗證。爲什麼context.Request.Context.Authentication.SignIn不生成cookie?

現在我們還想實現認證cookie以保護服務器上的靜態資源。我相信還有一百萬種其他方式可以做到這一點,但對資源的請求是直接鏈接到該資源的鏈接,因此我無法使用我的OAuth令牌或任何其他機制,這就是我們爲什麼要使用Cookie的原因......瀏覽器已經發送它們,不需要改變任何東西。

從我讀過的所有內容都可以使用OWIN管道進行承載令牌認證和Cookie認證。基本上,Web API將使用承載令牌,因爲所有的客戶端都會提供,並且服務器上的某些靜態資源請求將使用在所有請求上發送的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."); 
} 
... 

請記住,基於令牌的身份驗證正在運行,因此我認爲這是配置設置丟失或配置錯誤或流水線排序問題。

謝謝!

回答

0

我知道這是一個遲到的答案,但我們遇到了完全相同的問題。我的同事和我花了4個小時試圖找出原因。這是答案,希望可以拯救別人,把他們的頭靠在牆上。

檢查響應,你可以看到有Set-Cookie:.AspNet.Cookies=LqP1uH-3UZE-ySj4aUAyGa8gt ....但它沒有保存的cookie。你需要做的是,在你的ajax調用中,包含憑證。

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

我們使用的提取API,它看起來像下面

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