2012-03-26 37 views
6

我們對登錄頁面上的防僞令牌存在特定問題。如果用戶僅使用一個活動窗口登錄,那麼一切都很好,但是如果用戶在兩個不同的窗口中打開登錄頁面並從窗口A登錄(無問題將會登錄),並返回到此窗口中從窗口B登錄用戶將收到「所需的防僞標記未提供或無效」。Mvc3 Antiforgery令牌多選項卡

有沒有辦法解決這個問題,然後從視圖/控制器動作中刪除反僞造令牌?我們希望擁有令牌以增加安全性!

這是非常相似,這個問題然而這要求MVC2 MVC ValidateAntiForgeryToken multi-tabs problem

+0

我離開了你另一個答案的例子 - 我應該已經回答了我的問題! – 2013-09-03 16:28:38

回答

20

在MVC3或MVC4中的這種行爲是按設計的,但如上所述,它是非常不利於用戶的,但是在生產中,這個問題需要優雅地解決,應用程序需要處理這種奇怪的情況。此問題的解決方案是創建一個應用於登錄帖子的過濾器,以驗證用戶是否已登錄並將其帶到正確的頁面,否則它們將保留在登錄頁面上。

下面是過濾器的代碼屬性

/// <summary> 
/// Handle Antiforgery token exception and redirect to customer area if the user is Authenticated 
/// </summary> 
public class RedirectOnError : HandleErrorAttribute 
{ 
    /// <summary> 
    /// Override the on exception method and check if the user is authenticated and redirect the user 
    /// to the customer service index otherwise continue with the base implamentation 
    /// </summary> 
    /// <param name="filterContext">Current Exception Context of the request</param> 
    public override void OnException(ExceptionContext filterContext) 
    { 
     if (filterContext.Exception is HttpAntiForgeryException && filterContext.HttpContext.User.Identity.IsAuthenticated) 
     { 
      // Set response code back to normal 
      filterContext.HttpContext.Response.StatusCode = 200; 

      // Handle the exception 
      filterContext.ExceptionHandled = true; 

      UrlHelper urlH = new UrlHelper(filterContext.HttpContext.Request.RequestContext); 

      // Create a new request context 
      RequestContext rc = new RequestContext(filterContext.HttpContext, filterContext.RouteData); 

      // Create a new return url 
      string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { Controller = "CustomerArea", action = "Index" })).VirtualPath; 

      // Check if there is a request url 
      if (filterContext.HttpContext.Request.Params["ReturnUrl"] != null && urlH.IsLocalUrl(filterContext.HttpContext.Request.Params["ReturnUrl"])) 
      { 
       url = filterContext.HttpContext.Request.Params["ReturnUrl"]; 
      } 

      // Redirect the user back to the customer service index page 
      filterContext.HttpContext.Response.Redirect(url, true); 
     } 
     else 
     { 
      // Continue to the base 
      base.OnException(filterContext); 
     } 
    } 
} 

這是使用

​​
+0

我不明白如果用戶沒有登錄會發生什麼...因爲保留在日誌頁面上可能會再次導致異常。 – ilans 2014-07-16 16:53:52

+2

迴應IlanS - 代碼 if(filterContext.Exception是HttpAntiForgeryException && filterContext.HttpContext.User.Identity.IsAuthenticated) 只會在用戶登錄時應用重定向,否則非認證用戶的常規異常是拋出。 – MORCHARD 2015-04-23 14:54:53

+0

偉大的解決方案! – 2015-10-23 02:04:30

4

登錄之後,所有以前的令牌是無效的。這就是它應該如何工作。納茲接近正確的答案,除了cookie中的標記不存儲用戶名。只有表單中的令牌可以。正是由於這個問題:如果用戶登錄,所有現有的表單令牌都應該失效,但是使cookie本身無效將會太成問題並且用戶不友好。