2017-08-17 87 views
3

我有一個SPA我想升級到.NET 2.0的核心API網站升級cookie認證2.0

開箱.NET核心的有SPA很差Cookie身份驗證,因爲所有中間件假定你想重定向到/Account/Login

在單頁的應用程序的驗證重定向是無用的(沒有登錄頁) - 而不是我需要一個401響應,告訴客戶端JS要求用戶登錄

要解決這個問題。在.NET 1.1的核心,我不得不讓AutomaticChallenge火,然後覆蓋事件......

services.AddIdentity<AppUser, AppRole>(options => 
{ 
    var c = options.Cookies.ApplicationCookie; 
    c.AuthenticationScheme = "MyScheme"; 
    c.CookieName = "MyCookieName"; 
    c.AutomaticAuthenticate = true; 

    // This is a total cludge: AutomaticChallenge causes something deep in .NET to auto respond with a 302 redirect to ~/account/login 
    c.AutomaticChallenge = true; 
    c.LoginPath = PathString.Empty; // LoginPath defaults to ~/account/login 
    c.Events = new CookieAuthenticationEvents 
    { 
     // Override the 302 redirection with the 401 we actually want 
     OnRedirectToLogin = context => 
     { 
      context.Response.StatusCode = (int) HttpStatusCode.Unauthorized; 
      return Task.FromResult(0); 
     } 
    }; 
}) 

這是一個cludge,但它的工作。在.NET Core 2.0中它已被棄用。

我試過把它移到services.ConfigureApplicationCookie,但是當配置了cookie名稱和其他屬性時,CookieAuthenticationEvents.OnRedirectToLogin被忽略。

我試着將此移動到services.AddAuthentication(...).AddCookie(),建議爲in the official docs,但這些設置只是被忽略。 services.Configure<CookieAuthenticationOptions>表現相同的方式。

如何設置.NET Core 2.0 Web API,以便如果請求沒有有效的身份驗證Cookie,它將返回HTTP 401狀態?

+0

SPA始終存在工作表單/ cookies身份驗證問題,反之亦然。如果您使用SPA,則執行JSON Web令牌身份驗證並將所有後端服務作爲Web API運行。 – Jeyara

+1

@Jeyara你聽起來像這是SPA的一個基本問題。事實並非如此。 Cookies!=表單,服務是否返回持票人標記或Cookie應該是實現細節,而不是鎖定用戶名/密碼請求是表單還是JSON發佈。這裏甚至沒有問題:我有一個SPA可以與任何一個(都支持,所以一些密碼管理員工作)和成功從1.1設置cookie,但2失敗,因爲它假定我總是希望表單重定向。 – Keith

回答

-1

在Authentication 2.0堆棧中,應用程序Cookie的配置不再是identityOptions的一部分。請參閱Auth 2.0 Changes

services.ConfigureApplicationCookie(o => 
     { 
      o.Events = new CookieAuthenticationEvents() 
      { 
       OnRedirectToLogin = (ctx) => 
       { 
        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200) 
        { 
         ctx.Response.StatusCode = 401; 
        } 

        return Task.CompletedTask; 
       }, 
       OnRedirectToAccessDenied = (ctx) => 
       { 
        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200) 
        { 
         ctx.Response.StatusCode = 403; 
        } 

        return Task.CompletedTask; 
       } 
      }; 
     }); 
+0

感謝您的迴應,但如果您將問題閱讀到最後,您會看到我已經嘗試過。 – Keith

+0

我從我的API生產代碼複製/粘貼此代碼。不在你身邊工作?我有4個API以這種方式工作 –

+0

很酷。任何使用身份中間件從1.1升級? – Keith