Nithin B Nithin B - 23 days ago 5
Javascript Question

how to prevent HttpPost that is made from javascript that dosent belong to the project in mvc?

I have action method that should be having two features:


  1. It cant be accessed from browser URL directly or by get method(Which can be called from external java script files that doesn't belong to project as shown below).



I achieved above feature(Partially) by just adding [HttpPost] attribute to the action method.

Now I cant access directly using URL from browser. Or links click from external sources some thing like a HTML file having this get method call:

<a href="http://localhost:52225/Account/Delete/22">Click to play</a>


My action method:

[HttpPost]
public ActionResult Delete(int id)
{
EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
employeeBusinessLayer.DeleteEmployee(id);
return RedirectToAction("ListAllEmployees");
}


But I tried to access using java-script post and I was able to access it.

Here is the code. This code is also in an external file and doesn't belong to project.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function jsfunction()
{
$.post("http://localhost:52225/Account/Delete", {id: 22}, function (data) {
alert("Please click again");
});
};
</script>
<style type="text/css">
a.button
{
font: bold 11px Arial;
text-decoration: none;
background-color: #EEEEEE;
color: #333333;
padding: 2px 6px 2px 6px;
border-top: 1px solid #CCCCCC;
border-right: 1px solid #333333;
border-bottom: 1px solid #333333;
border-left: 1px solid #CCCCCC;
}
</style>
</head>
<body>
<a onclick="jsfunction()" href="javascript:void(0);" class="button">Click to play</a>
</body>
</html>


So I feel my problem is not yet solved an hacker can write the above code and will be able to access the HttpPost method.

How to prevent this?

NOTE: I mean I want to give access only to the requests made from button in cshtml view's and also belong to the same project.

Answer

Use MVC Anti Forgery Token to secure it.

In your .cshtml file include @Html.AntiForgeryToken() and then in your Action method check for the Anti Forgery Token:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
    EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
    employeeBusinessLayer.DeleteEmployee(id);
    return RedirectToAction("ListAllEmployees");
}