Friday, December 13, 2019

AntiForgeryToken


Cyber Security is a challenging business problem to solve.  Recently, I created the foundation for telematics product to gain the customer confidence.

As .NET engineer, I was looking for out of box solution from Microsoft and here you go 'AntiForgeryToken' With open source culture of .NET Core, it is publicly available at https://github.com/aspnetboilerplate/aspnetboilerplate/issues/1297

By design, AntiForgeryToken generates a hidden form field of anti-forgery token to validate the submitted form. The anti-forgery token can be used to help protect your application against cross-site request forgery.

Let us see the code sample.  It's quite simple to implement by just adding the ValidateAntiForgeryToken attribute to your methods. Flip side is the cost of checking for the token with every request, not just with the HttpPost methods.

[HttpPost]  
[ValidateAntiForgeryToken]  
public ActionResult CreateSensor(Sensor sensor)  
{
  if (ModelState.IsValid)  
  {
    //business logic here...
  }
  return View(ModelName);
}

Alternative solution is to add AutoAntiForgeryToken to the controller classes as below

[AutoAntiForgeryToken]
public class TelematicsDeviceController : Controller
{
   //core logic here...
}

By doing so, the attribute checks only the dangerous methods i.e. only methods that aren't a GET or methods never use TRACE, OPTIONS and HEAD

Happy Cyber Security Coding Fix !!

No comments:

Post a Comment