Getting Started With ASP.Net Web API 2 : Day 8

Introduction

Before reading this article, I highly recommend reading the previous parts:

In this article we will learn about Cross-Site Request Forgery (CSRF) Protection. How to implement CSRF protection against the data submitted from MVC pages to the Web API  endpoints. Since we are familiar with the CSRF protection functionality in the ASP.NET MVC, in MVC we use the System.Web.Helpers.AntiForgery class, this is the part of System.Web.WebPages.

This class generates the two tokens. The first one is a cookie and the other is a string-based token. These tokens are embedded into a form or a request header. For the prevention of an attack the Web API includes both of the tokens that will validate on the server side.  

Since we know the token generation within the context of a MVC application, let's try to understand using an example.

  1. <form id="myForm">    
  2.     @Html.AntiForgeryToken()       
  3. </form>  

The helper uses the AntiForgery class and writes the cookies token to the response and generates a field name _RequestVerificationToken, that is sent along to the form data. For the validation we call the static Validation method on the Antiforgery class, this class is called without the parameter and it uses the HttpContext.Current. In the Web API a custom handler is responsible for the CSRF token validation and it can intercept every request as as enter in the Web API, it will perform the checks and continue with the pipeline execution.  

So before starting this article, I suggest you read my previous articles on the Web API, they make the concepts more clear. 

We can now start the coding to learn the the concept of CSRF.
 

Prerequisites

There are the following things we need to use when developing a Web API 2 application.

  • Visual Studio 2013

  • ASP.NET Web API 2

Getting Started

In this section we will follow some important procedures and these are:

  • Create ASP.NET Web API

  • Add Web API 2 Controller

  • Add a class inside the model.

We need to use a basic procedure to do CSRF protection.

Step 1

Open the Visual Studio 2013 and click New Project.

Step 2

Select the ASP.NET Web Application and provides a nice name for the project.

 NewProject

Step 3

Select the Web API template and click the OK button, by default it will choose MVC along with the Web API.
 
SelectTemplate

Step 4

Right-click on the Model folder and add a Student class to the model where the name fields are defined.
  1. namespace CSRF.Models  
  2. {  
  3.     public class Student  
  4.     {  
  5.         public string Name { getset; }  
  6.     }  
  7. }  
Step 5

Right-click on the Controller folder and select the Web API 2 empty controller and provide a nice name. For this project I took valueController and added a HomeController and StudentController inside them.
  1. namespace CSRF.Controllers  
  2. {  
  3.     public class FormController : ApiController  
  4.     {  
  5.         public Student Post(Student st)  
  6.         {  
  7.             return st;  
  8.         }  
  9.     }  
  10.         public class StudentController : ApiController  
  11.         {  
  12.             public Student Post(Student stData)  
  13.             {  
  14.                 return stData;  
  15.             }  
  16.         }  
  17.          
  18.     }  
Step 6

Create a HttpRequestMessageExtensions class.
  1. namespace CSRF  
  2. {  
  3.     public static class HttpRequestMessageExtensions  
  4.     {  
  5.         public static bool IsAjaxRequest(this HttpRequestMessage req)  
  6.         {  
  7.             IEnumerable<string> headers;  
  8.             if (req.Headers.TryGetValues("X-Requested-with"out headers))  
  9.             {  
  10.                 var header = headers.FirstOrDefault();  
  11.                 if (!string.IsNullOrEmpty(header))  
  12.                 {  
  13.                     return header.ToLowerInvariant() == "xmlhttprequest";  
  14.                 }  
  15.             }  
  16.             return false;  
  17.         }  
  18.     }  
  19. }  
Step 7

And again a AntiForgeryHandler class.
  1. namespace CSRF  
  2. {  
  3.     public class AntiForgeryHandler: DelegatingHandler  
  4.     {  
  5.         protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage req, CancellationToken cancellationToken)  
  6.         {  
  7.             string cookieToken = null;  
  8.             string formToken = null;  
  9.             if (req.IsAjaxRequest())  
  10.             {  
  11.                 IEnumerable<string> tokenHeaders;  
  12.                 if(req.Headers.TryGetValues("_RequestVerificationToken"out tokenHeaders))  
  13.                 {  
  14.                     var cookie = req.Headers.GetCookies(AntiForgeryConfig.CookieName).FirstOrDefault();  
  15.                     if (cookie != null)  
  16.                     {  
  17.                         cookieToken = cookie[AntiForgeryConfig.CookieName].Value;  
  18.                     }  
  19.                     formToken = tokenHeaders.FirstOrDefault();  
  20.                 }  
  21.             }  
  22.             try  
  23.             {  
  24.                 if (cookieToken != null && formToken != null)  
  25.                 {  
  26.                     AntiForgery.Validate(cookieToken, formToken);  
  27.                 }  
  28.                 else  
  29.                 {  
  30.                     AntiForgery.Validate();  
  31.                 }  
  32.             }  
  33.             catch (HttpAntiForgeryException)  
  34.             {  
  35.                 return req.CreateResponse(HttpStatusCode.Forbidden);  
  36.             }  
  37.   
  38.             return await base.SendAsync(req,cancellationToken);  
  39.               
  40.         }  
  41.     }  
  42. }  
We have now create both of the classes. HttpRequestMessage does have a built-in way to check the the request, if it comes in AJAX. A simple form and AJAX request, both utilize the anti-CSRF token. A traditional form, the HTML helper renders a hidden input field and an anti-forgery token is submitted along the form data automatically and the AJAX request explicitly reads the token value from the rendered hidden input field and is attached to the request in a custom header field.
  1. <div class="row">  
  2.     <div class="col-md-4">  
  3.         <h2>CSRF Html Page</h2>  
  4.         <div>  
  5.             <form id="form1" method="post" action="/api/form" enctype="application/x-www-form-urlencoded">  
  6.                 @Html.AntiForgeryToken()  
  7.                 <div>  
  8.                     <label for="name">Name</label>  
  9.                 </div>  
  10.                 <div>  
  11.                     <input type="text" name="name" placeholder="Enter some data" />  
  12.                 </div>  
  13.                 <div>  
  14.                     <button id="postData" name="postData">Post to Form</button>  
  15.                 </div>  
  16.             </form>  
  17.         </div>  
  18.     </div>  
  19.   
  20.     <div id="jsData" class="col-md-6">  
  21.         <h2> Ajax Safe</h2>  
  22.         @Html.AntiForgeryToken()  
  23.         <input id="ItemJs" type="text" disabled="disabled" name="text"  placeholder="Enter some data" />  
  24.         <div>  
  25.             <button id="postJS" name="postJS"> Post JS</button>  
  26.         </div>  
  27.     </div>  
  28. </div>  
  29. @section scripts {  
  30.     <script type="text/javascript">  
  31.         $(function () {  
  32.             $("#postJS").on("click", function () {  
  33.                  
  34.                 $.ajax({  
  35.                     dataType: "json",  
  36.                     data: JSON.stringify({ name: $("#ItemJs").val() }),  
  37.                     type: "POST",  
  38.                     headers: {  
  39.                         //"_RequestVerificationToken": $("#jsData input[name='_RequestVerificationToken']").val()  
  40.                         "_RequestVerificationToken":"hello"  
  41.                     },  
  42.                     contentType: "application/json; charset=utf-8",  
  43.                     url: "/api/Student"  
  44.                     
  45.                 }).success(function (res) {  
  46.                     alert(res.name);  
  47.                 });  
  48.             });  
  49.         });  
  50.     </script>  
  51. }  
Output

output1

Enter the data inside the Name and hit the button. The Form controller will handle the operation and display the data.

output2
 
Further Reading

Getting Started with ASP.NET Web API 2 : Day 9


Similar Articles