Asp.net-Mvc-5

Web API 2 OWIN Bearer Token cookie的用途?

  • January 4, 2014

我正在嘗試了解 MVC 5 中單頁應用程序模板中新的 OWIN Bearer Token 身份驗證過程。如果我錯了,請糾正我,對於 OAuth 密碼客戶端身份驗證流程,Bearer Token 身份驗證通過檢查 http 授權請求標頭來工作對於承載訪問令牌程式碼來查看請求是否經過身份驗證,它不依賴 cookie 來檢查特定請求是否經過身份驗證。

根據這篇文章:

使用 Web API 範例進行 OWIN 不記名令牌身份驗證

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
   using (IdentityManager identityManager = _identityManagerFactory.CreateStoreManager())
   {
       if (!await identityManager.Passwords.CheckPasswordAsync(context.UserName, context.Password))
       {
           context.SetError("invalid_grant", "The user name or password is incorrect.");
           return;
       }

       string userId = await identityManager.Logins.GetUserIdForLocalLoginAsync(context.UserName);
       IEnumerable<Claim> claims = await GetClaimsAsync(identityManager, userId);
       ClaimsIdentity oAuthIdentity = CreateIdentity(identityManager, claims,
           context.Options.AuthenticationType);
       ClaimsIdentity cookiesIdentity = CreateIdentity(identityManager, claims,
           _cookieOptions.AuthenticationType);
       AuthenticationProperties properties = await CreatePropertiesAsync(identityManager, userId);
       AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
       context.Validated(ticket);
       context.Request.Context.Authentication.SignIn(cookiesIdentity);
   }
}

GrantReourceOwnerCredentials 函式不僅使用以下行組成票證: context.Validated(ticket); 但它也組成一個 cookie 身份,並使用以下行將其設置為 cookie: context.Request.Context.Authentication.SignIn(cookiesIdentity);

所以我的問題是,這個函式中 cookie 的確切目的是什麼?AuthenticationTicket 不應該足以用於身份驗證目的嗎?

在 SPA 模板中,實際上啟用了兩種獨立的身份驗證機制——cookie 身份驗證和令牌身份驗證。這啟用了 MVC 和 Web API 控制器操作的身份驗證,但需要一些額外的設置。

如果您查看 WebApiConfig.Register 方法,您將看到這行程式碼:

   config.SuppressDefaultHostAuthentication();

這告訴 Web API 忽略 cookie 身份驗證,從而避免了許多問題,這些問題在您在問題中發布的連結中進行了解釋:

“…SPA 模板也將應用程序 cookie 中間件啟用為活動模式,以啟用 MVC 身份驗證等其他場景。因此,如果請求具有會話 cookie 但沒有承載令牌,則 Web API 仍將通過身份驗證。這可能不是你的因為你的 API 很容易受到 CSRF 攻擊。另一個負面影響是,如果請求未經授權,兩個中間件組件都會向它提出挑戰。cookie 中間件會將 401 響應更改為 302 以重定向到登錄頁面。這也不是你想要的 Web API 請求。”

因此,現在config.SuppressDefaultHostAuthentication()呼叫需要授權的 Web API 呼叫將忽略隨請求一起自動發送的 cookie,並查找以“Bearer”開頭的 Authorization 標頭。MVC 控制器將繼續使用 cookie 身份驗證,並且對令牌身份驗證機制一無所知,因為它不太適合一開始的網頁身份驗證。

引用自:https://stackoverflow.com/questions/20926979