maces maces - 1 year ago 45
ASP.NET (C#) Question

Should I secure div with inputs against CSRF

Greetings I'd like to clear out am not a security expert neither i am an ethical or black hat hacker or what so ever related to the security field what i know is that when creating webpages with forms a measurement is taken to protect forms from Cross Site Request Forgery "CSRF" but in some scenarios a div element containing input elements and button or clickable divs can be used to do the exact job.

usually when coding the form it will be protected against CSRF in ASP.NET using


inside the form declaration in razor page

The question is : is it useful or will it work to perform same procedure with a given div that contains inputs and button that will perform an AJAX call or not ????

Thanks in advance for answers and please feel free to correct my information or show any mistake in my assumption

Answer Source

Yes, the client side solution does not matter at all. CSRF is a server-side vulnerability, any call to a server that changes server state (data, basically, but also things like login, privilege level changes, etc.) is vulnerable to CSRF if not protected.

In AJAX requests, you have to send the token yourself. Using jQuery, you can use $.ajaxSetup() and the beforeSend hook to capture any state-chaning request and add the token automatically (this applies to POSTs in general, but it can be PUT, DELETE, even GET if the application uses GETs to change stuff). The benefit of using beforeSend is that you only have to do it once and don't need to remember it anymore. The token in this case can be generate in the page with @Html.AntiforgeryToken() as usually, javascript can take it from there.

A slightly special case is when you send json data (the content-type for the request is application/json and it's not www-url-encoded). The standard attribute [ValidateAntiForgeryToken] cannot take the token from json (and it also cannot take it from a request header, should you decide that's the best option to pass it). In this case, you can implement a custom validation attribute, but that's easy, you only have to implement where to get the token from, for the actual validation you can still use the standard AntiForgery.Validate() method.