2017-08-28 109 views

回答

1

看來你需要的是通過檢查HttpContext.Request.HttpMethod請求創建一個自定義過濾器類,它實現IAuthorizationFilter所有POST方法:

public class ValidateAntiForgeryTokenEveryPost : IAuthorizationFilter 
{ 
    public void OnAuthorization(AuthorizationContext context) 
    { 
     if (context.HttpContext.Request.HttpMethod == "POST") 
     { 
      System.Web.Helpers.AntiForgery.Validate(); 
     } 
    } 
} 

然後,添加新濾波器FilterConfig類:

public class FilterConfig 
{ 
    public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
    { 
     filters.Add(new ValidateAntiForgeryTokenEveryPost()); 
    } 
} 

還要確保自定義過濾器已經註冊在Global.asax代碼:

protected void Application_Start() 
{ 
    // other settings 

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 

    // other settings 
} 

通過使用上面給出的全局過濾,所有POST方法請求都自動檢查AntiForgeryToken,不管@Html.AntiForgeryToken()不存在內部視圖的網頁。

附錄1:

它可以排除CSRF令牌檢查某些操作,你需要的是防止Validate方法,而自定義屬性類存在執行。首先,創建一個自定義屬性類的驗證檢查:

[AttributeUsage(AttributeTargets.Method)] 
public class ExcludeAntiForgeryCheckAttribute : Attribute 
{ 
    // other stuff 
} 

之後,使用ActionDescriptor.GetCustomAttributes獲得自定義屬性類型創建上面:

public class ValidateAntiForgeryTokenEveryPost : IAuthorizationFilter 
{ 
    public void OnAuthorization(AuthorizationContext context) 
    { 
     // adapted from Darin Dimitrov (/a/34588606/) 
     bool isValidate = !context.ActionDescriptor.GetCustomAttributes(typeof(ExcludeAntiForgeryCheckAttribute), true).Any(); 

     // use AND operator (&&) if you want to exclude POST requests marked with custom attribute 
     // otherwise, use OR operator (||) 
     if (context.HttpContext.Request.HttpMethod == "POST" && isValidate) 
     { 
      System.Web.Helpers.AntiForgery.Validate(); 
     } 
    } 
} 

然後你可以裝飾應從CSRF驗證被免除任何方法令牌:

[HttpPost] 
[ExcludeAntiForgeryCheck] 
public ActionResult Index(ViewModel model) 
{ 
    // other stuff 

    return View(model); 
} 

參考文獻:

Check CRSF token by default in ASP.NET MVC(標準版)

Securing all forms using AntiForgeryToken(基於屬性的版本)

+0

非常感謝。還有一個問題。我是MVC的新手,所以我不確定我需要創建自定義過濾器類的文件夾。你能告訴我這個嗎? –

+0

我認爲你的自定義過濾類可以在'App_Start'目錄或你想要的任何目錄下創建,只要使用了項目的根名稱空間而不是'ProjectName.App_Start'或'ProjectName.FolderName'。 –

+0

非常感謝。@Tetsuya Yamamoto –

1

我不這麼認爲。對於每個請求我們需要檢查令牌。 請嘗試在視圖文件中使用以下代碼。

@ Html.AntiForgeryToken()

+0

我們可以在每個視圖頁面實現。但我想在Global.asax文件中實現相同的功能。 –