Using ASP.NET MVC's AntiForgeryToken in HTML Templates

Posted by: Malcolm Sheridan , on 7/26/2010, in Category ASP.NET MVC
Views: 36147
Abstract: The following article demonstrates how to use ASP.NET MVC anti forgery tokens in a client side template.
A great feature in ASP.NET MVC is the AntiForgeryToken. This Generates a hidden form field (anti-forgery token) that is validated when the form is submitted. The anti-forgery token can be used to help protect your application against cross-site request forgery. To use this feature, all you need to do is add the following HTML helper to your form so it is submitted as part of the form post:
<%: Html.AntiForgeryToken() %>
 
This is great if you're running the page in an aspx page, but if you use a client template engine, such as jTemplates, you cannot use ASP.NET MVC syntax in a standard HTML page, but you still want to be able to get all the security goodness that comes with the AntiForgeryToken. Well in this article I'll demonstrate one way of doing this.
To see this in action, I'm going to create a small ASP.NET MVC 2 website. If you haven't got Microsoft Visual Studio 2010, you can download the Express edition here. You'll also need a copy of jTemplates which can be downloaded from here.
I've created a stock standard MVC project and added a folder called Templates. I've added a HTML page which will contain the HTML code plus HTML. If I added this code to use the AntiForgeryToken, it would be rendered out as plain text:
<form method="post" action="/Home/SubmitForm">   
    <%: Html.AntiForgeryToken("DynamicToken") %>
    <input type="text" name="givenName" id="givenName" />
    <input type="submit" value="Submit" />
</form>
 
Here's the result:
Result
That's not what I want! To get this to work, I need to generate the AntiForgeyToken from the aspx page, and pass it into the HTML template. This is easy when you use jTemplates. Here's what the template should look like:
<form method="post" action="/Home/SubmitForm">
    {$P.RequestVerificationToken}<br />
    <input type="text" name="givenName" id="givenName" />
    <input type="submit" value="Submit" />
</form>
 
Here's the complete code below:
<script language="javascript" src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script language="javascript" src="../../Scripts/jquery-jtemplates.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
 
        $(function () {
            helper.GenerateForm();
        });
 
        var helper = function () {
            return {
                GenerateForm: function () {
                    var token = '<%: Html.AntiForgeryToken("DynamicToken") %>';
                    $("#generateSomeForm").setTemplateURL("/Templates/CustomForm.htm")
                                          .setParam("RequestVerificationToken", token)
                                          .processTemplate();
                }
            }
        } ();
       
    </script>   
    <div id="generateSomeForm"></div>
 
What's happening in the code above is the value of the AntiForgeryToken is still being evaluated on the server because it's running in the aspx page. Its value is being stored in the JavaScript by the following line:
token = '<%: Html.AntiForgeryToken("DynamicToken") %>';
The value is then being passed into the HTML page as a parameter in the jTemplates object. By doing it this way, we get the benefits of the AntiForgeryToken running in an HTML page. Now our HTML form is nice and secure. The entire source code of this article can be downloaded over here
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Mohammed alaraimi on Tuesday, November 30, 2010 5:28 AM
I want javascript code which I do overmouse will display the explination moving on the seprat cell about that link
Comment posted by jkkkkkkkkkkkkkkk on Friday, January 24, 2014 6:41 AM
jkjjjjjj

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel