ilhan DEMİRTEPE
ParamTech
Published in
2 min readOct 9, 2020

--

What is CSRF(Cross-site request forgery)

Cross-site request forgery (also known as CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform. It allows an attacker to partly circumvent the same origin policy, which is designed to prevent different websites from interfering with each other.

Mvc Ajax Security with CSRF

İf you want prevent CSRF you use TOKEN. For example Mvc project you use AntiForgeryToken()

All The Code .

public class HomeController : Controller

{

public ActionResult Index()

{

return View();

}

[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult IndexPost(string myValue)

{

return Json(new { sendValue = myValue });

}

}

@{
ViewBag.Title = "Home Page";
}
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
@Html.AntiForgeryToken()
}
<button type="button" class="btn-default" value="Click Me" onclick="GetToken()"></button>
<script src="~/Scripts/jquery-3.3.1.js"></script>
<script type="text/javascript">
function GetToken()
{

var form = $('#myForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url:'/Home/IndexPost/',
type: 'POST',
data: {
__RequestVerificationToken: token,
myValue: 'My data'
},
success: function (result) {
console.log(token);
alert(result.sendValue);
}
});
return false;
};
</script>

--

--