2015-10-07 44 views
1

我正在開發一個帶有AngularJs前端的ASP.NET MVC 6 Web API應用程序。MVC6防止未經授權的重定向

當我離開會議十年,或者我試圖調用未經授權的Web API操作時,我希望收到401狀態碼。 取而代之,我得到一個302,並嘗試重定向到登錄的默認路徑(「/帳戶/登錄」)。

所以我需要在Angular中處理這個問題。

從其他論壇的帖子在這裏和谷歌上搜索,我發現有些人使用startup.cs解決自己的問題:

services.Configure<CookieAuthenticationOptions>(options => 
{ 
    options.LoginPath = PathString.Empty; 
}); 

沒有運氣我。

我用的身份爲認證後端,甚至加入

services.ConfigureIdentityApplicationCookie(options => 
{ 
    options.LoginPath = PathString.Empty; 
}); 

不給我預期的結果。 ASP.NET文檔建議以這種方式返回401.

使用1.0.0-beta7 CLR x86,IIS Express。

回答

3

對我來說,它只是將AutometicAuthenticate設置爲false。

services.Configure<IdentityOptions>(options => 
     { 
      options.Cookies.ApplicationCookie.AutomaticAuthenticate = false; 
      options.Cookies.ApplicationCookie.AutomaticChallenge = false; 
      options.Cookies.ApplicationCookie.LoginPath = PathString.Empty; 
     }); 
6

編輯:@EZI提出的解決方案是正確的。 下面我的答案,這不適用於最近的版本。

終於!我找到了解決方案!

爲了完整起見,我從aspnet/Identity github中的源代碼中找到了此評論。

// If the LoginPath is null or empty, the middleware will not look for 401 Unauthorized status codes, and it will not redirect automatically when a login occurs. 

這給我錯誤的方向。

與ConfigureIdentityApplicationCookie」選項調試挖,我發現有一個代表的‘通知’屬性

OnApplyRedirect 

賓果!

現在我可以控制重定向了。

services.ConfigureIdentityApplicationCookie(options => 
{ 
    options.LoginPath = PathString.Empty; 
    options.Notifications = new CookieAuthenticationNotifications { 
     OnApplyRedirect = context => { context.Response.StatusCode = 401; } 
    }; 
}); 

這也許不是處理問題的好辦法,但最後我收到401未經授權當web.api動作叫做無認證。

+0

爲RC1 – FLCL

+0

不工作是否有人有關於如何在asp.net核心的發行版本解決了信息工作的? – Maris

+0

這似乎對我有效:'services.AddIdentity (c => c.Cookies.ApplicationCookie.LoginPath = PathString.Empty' – GeorgDangl

1

我的解決方案是類似於@Ezi

證實RC2

services.AddIdentity<IdentityUser, IdentityRole>(options => 
    { 
     options.Cookies.ApplicationCookie.AutomaticChallenge = false; 
    });