How to protect against CSRF by default in ASP.NET MVC 4?

前端 未结 4 474
时光取名叫无心
时光取名叫无心 2021-01-30 14:38

Is there a way to ensure ASP.NET MVC 4 forms are protected against CSRF by default?

For instance, is there a way to have AntiForgeryToken automatically

4条回答
  •  情深已故
    2021-01-30 15:04

    You can use a filter provider with a condition that the filter ValidateAntiForgeryTokenAttribute() be applied whenever HttpContext.Request.HttpMethod == "POST".

    I essentially followed the generic approach described by Phil Haack, and added the appropriate condition:

    // Ensure all POST actions are automatically decorated with the ValidateAntiForgeryTokenAttribute.
    ( c, a ) => string.Equals( c.HttpContext.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase ) ?
     new ValidateAntiForgeryTokenAttribute() : null
    

提交回复
热议问题