Click here to Skip to main content
15,867,771 members
Articles / Web Development / ASP.NET

Protect Your Form Postback with Anti-Forgery

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
19 Sep 2012CPOL2 min read 26.7K   6   6
Secure a web page postback from malicious exploits.

To secure a web page postback from malicious exploits, we can add a security token as a hidden field to the form or a cookie. When a postback is received, this token is validated to make sure that the request is not a cross-site request forgery.

When working with Razor Web Pages and WebMatrix, we can find a handy helper which provides this implementation right out of the box. The AntiForgery helper gives us the capability to create and validate the secured encrypted token by just using a couple of lines of code. This helper is found in the System.Web.Helpers.dll assembly, and it should be added automatically as a reference to your project in the bin folder.

To show you how to use this helper, open a web page on WebMatrix and add the following mark-up:

XML
@{
    // Validation token test during postback;
    if(IsPost){
        try
        {
            AntiForgery.Validate();
        }
        catch(Exception ex)
        {
            ModelState.AddFormError(ex.Message);
        }
     
        if(ModelState.IsValid)
        {
            Page.SuccessMessage = "Token validated!";           
        }        
    }    
}
<!DOCTYPE html>
<html lang="en">
    <head>  
    </head>
<body>
<div class="message-error">@Html.ValidationSummary()</div>
<div class="message-success">@Page.SuccessMessage</div>
<form method="post" action="">
    Full Name:<input type="text" name="username" id="username"/><br/>
    EMail:<input type="password" name="username" id="username"/><br/>
   @AntiForgery.GetHtml()
    <input type="submit" name="submit" value="Send"/>   
</form>
</body>
</html>

This is a simple contact page with two fields. This page is available to the public on the internet, and we would like to prevent any type of exploits. In order to do that, we have added this line of code in between the form tags:

@AntiForgery.GetHtml()

If you look at the page source after it has rendered on the browser, you can see that a hidden field has been added:

The _RequestVerificationToken field contains an encoded encrypted token. In addition, a cookie with the same information has been created. This allows the helper to cross check the token in both the form and cookie.

To validate the token during the post back, we use this code:

C#
try
{
    AntiForgery.Validate();
}
catch(Exception ex)
{
    ModelState.AddFormError(ex.Message);
}

The call to Validate() raises an exception if the token is not valid. At this point, the code can stop doing any additional logic and just present an error using the ValidationSummary method from the Html helper.  If the token is successfully validated, we check the ModelState.IsValid method and continue the intended logic which for this example is just adding the contact information to the system.

I hope you can find this helper very useful for your own implementation.

This article was originally posted at http://ozkary.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect OG-BITechnologies
United States United States
Software engineer, author & speaker who enjoys mentoring, learning, speaking and sharing with others about software development technologies. Microsoft MVP.

My Blog

Comments and Discussions

 
GeneralMy vote of 5 Pin
Kanasz Robert20-Sep-12 1:35
professionalKanasz Robert20-Sep-12 1:35 
QuestionVS2010 and System.Web.Helpers.dll Pin
JBoada19-Sep-12 15:50
JBoada19-Sep-12 15:50 
AnswerRe: VS2010 and System.Web.Helpers.dll Pin
ozkary20-Sep-12 8:09
ozkary20-Sep-12 8:09 
AnswerFormatting? Pin
Clifford Nelson19-Sep-12 8:21
Clifford Nelson19-Sep-12 8:21 
AnswerRe: Formatting? Pin
Clifford Nelson19-Sep-12 10:33
Clifford Nelson19-Sep-12 10:33 
GeneralRe: Formatting? Pin
ozkary20-Sep-12 7:56
ozkary20-Sep-12 7:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.