Asp.net-Mvc
一起使用不記名令牌和 cookie 身份驗證
我有一個單頁應用程序 - 或多或少基於 MVC5 SPA 模板 - 使用不記名令牌進行身份驗證。
該站點還有幾個需要保護的傳統 MVC 頁面,但使用cookie 身份驗證。
在 Startup.Auth 我可以啟用兩種類型的授權:
app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOAuthBearerTokens(OAuthOptions);但是,這似乎有一個副作用,因為每當從 SPA 發送 AJAX 請求時,它都會發送標頭中的不記名令牌和cookie。
而我真正想要的行為是只有承載令牌用於 WebAPI 呼叫,只有 cookie 用於 MVC 呼叫。
我還希望 MVC 呼叫在未授權時重定向到登錄頁面(設置為 CookieAuthenticationOption),但顯然我不希望在進行 API 呼叫時發生這種情況。
有沒有辦法在一個應用程序中進行這種類型的混合模式身份驗證?也許通過路徑/路由過濾器?
我想我解決了這個問題:-
Startup.Auth 正在連接 OWIN 管道,因此在其中包含 Cookie 和令牌是正確的。但是對 cookie 選項的一項更改指定了它應該應用於的身份驗證類型:
CookieOptions = new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie };然後我需要將 WebAPI 配置為僅使用令牌:
public static void Configure(HttpConfiguration config) { // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); }這似乎達到了我想要的。WebAPI 只使用不記名令牌而不使用 cookie,一些傳統的 MVC 頁面在登錄後使用 cookie(使用 AuthenticationManager)。