我們有一個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.");
}
...
請記住,基於令牌的身份驗證正在運行,因此我認爲這是配置設置丟失或配置錯誤或流水線排序問題。
謝謝!