Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing crf attacks on ajax requests in asp.net web forms

How can I prevent csrf attacks on ajax requests in a asp.net webforms application

like image 525
Sivakumar Avatar asked Feb 15 '23 03:02

Sivakumar


2 Answers

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);
}
});
like image 113
Murali Murugesan Avatar answered Mar 07 '23 23:03

Murali Murugesan


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);
   }
});
like image 35
Superzadeh Avatar answered Mar 07 '23 23:03

Superzadeh