Rules

Secret ingredients to quality software

Edit
Info

Do you use Anti Forgery Tokens on any page that takes a POST?

Created on 08 Mar 2013 | Last updated by Tiago Araujo on 08 Mar 2013 03:02 PM (about 8 years ago)

To prevent cross-site request forgery (XSRF), you should use Html.AntiForgeryToken. On the action which takes the post request, place the ValidateAntiForgeryToken attribute to enable the request to validate. Doing this ensures that the post is a direct response to the page that was given to this user so only verified posts will be processed.

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
 }

Figure: Bad Example – The page is potentially vulnerable to XSRF attacks. Any post will be accepted by the server

View:

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <p>
        
            <input type="submit" value="Create"/>
    </p>
}

Controller:

[ValidateAntiForgeryToken]
public ActionResult Create(CreateModel model)
{
    // save data
}

Figure: Good Example – The page is no longer vulnerable to XSRF attacks

Damian BradyDamian Brady

We open source. This page is on GitHub