How can I prevent csrf attacks on ajax requests in a asp.net webforms application
You could create a token and keep it in Session["CSRF"] and render the same in HiddenField of everypage.
protected HiddenField CSRF { get; set; }
protected void page_load(object s, args[] e) {
if(Session["CSRF"]!=null) {
this.CSRF=Session["CSRF"];
}
else {
Session["CSRF"]=Guid.NewGuid().ToString();
this.CSRF=Session["CSRF"];
}
}
So whenever you send a request add it as a data parameter and check it in the server side code.
Pass this CSRF HiddenField id for every request.
For ASP.Net Ajax calls you could use ViewState["CSRF"]
, since by default update panel will send the Page's viewstate also :)
for jQuery ajax
var csrf_token = '<%= csrf_value %>';
The below code will add this token for all the ajax requests
$("body").bind("ajaxSend", function(elm, xhr, s){
if (s.type == "POST") {
xhr.setRequestHeader('X-CSRF-Token', csrf_token);
}
});
You should have a look at this link: Preventing Cross-Site Request Forgery (CSRF) Attacks
In short: anti-forgery tokens, which are provided as part of the ASP.NET MVC framework. Since however you are using webforms, it might be a little bit more complicated but it is possible to have an ASP.NET website running both webforms and MVC (or have a look at this answered question: AntiForgery implementation in Asp.net Forms).
EDIT: Also, to protect jQuery calls, you could use an anti forgery token and print it client side (as described here:
var csrf_token = '<%= token_value %>';
$("body").bind("ajaxSend", function(elm, xhr, s){
if (s.type == "POST") {
xhr.setRequestHeader('X-CSRF-Token', csrf_token);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With