Asp.net-Mvc
Mvc3 Antiforgery 令牌多選項卡
我們在登錄頁面上遇到了與防偽令牌有關的特定問題。如果使用者僅使用一個活動視窗登錄,則一切正常,但是如果使用者在兩個不同的視窗中打開登錄頁面並從視窗 A 登錄(沒有問題將登錄),然後在此視窗中返回從視窗 B 登錄使用者將收到“未提供所需的防偽令牌或無效”。
有沒有辦法解決這個問題,然後從視圖/控制器操作中刪除防偽令牌?我們希望擁有令牌以提高安全性!
這與這個問題非常相似,但是這是針對 mvc2 MVC ValidateAntiForgeryToken 多選項卡問題提出的
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); } } }這是使用範例
[HttpPost] **[RedirectOnError]** [ValidateAntiForgeryToken] public ActionResult LogOn(LogOnViewModel model, UserSessionState session, string returnUrl) { ..... }