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

前端 未结 4 539
时光取名叫无心
时光取名叫无心 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:28

    One way to do it would be to modify the T4 templates in ASP.NET MVC that create forms, to have them insert this code automatically:

    <% using(Html.Form("UserProfile", "SubmitUpdate")) { %>
        <%= Html.AntiForgeryToken() %>
        
    <% } %>
    

    And of course, you need the corresponding attribute on the controller method:

    [ValidateAntiForgeryToken]
    public ViewResult SubmitUpdate()
    {
        // ... etc
    }
    

    It's really not that difficult to retrofit an application in this manner, unless it's unusually large. The last application I wrote in MVC would probably take me a couple of hours to retrofit.

提交回复
热议问题