Search code examples
asp.net-mvccsrfantiforgerytoken

Is a good practice to avoid CSRF doing this? (ASP.NET MVC 3)


I have one question about the use of AntiForgeryToken provided by MVC 3.

I will try to explain my idea.

The basic idea is an Ajax button to "mark as favorite" one (or more) item from a Catalog. So I have a grid with the entire list of items, and each of this items has a button to make as favorite.

Well... my idea implementation is this:

When the user push the favorite button, this send a GET request to the server to retrieve a partialView with AntiForgeryToken (all of this is transparent to the user because happen on the background).

So when the Form is loaded the site automatically submit (POST) the data (the id of the item and the antiforgerytoken) to mark this item as favorite (again... this happen in background, so the user never see anything).

This is the idea over request/response on Firebug:

GET http://localhost/User/Favorite/Mark?url=156

Response from GET:

<form action="/User/Favorite/Mark?url=156" method="post">
<input name="__RequestVerificationToken" type="hidden" value="WVXhVJJ3VNB8HrZQ6CZBPt35z2zvDjaHmlYWrnCvJoDUgeWMEGUGwm3clCD27vFAsxbs0upiRdVdo9Wsus Z7B6SU NQgV3iSYTUtE/EREWqT1Is/kwNZpdNf/3Pi7fD572pO89lTdYEjL0OlzmPJ5tmRQEUq/oMbuj0MnmPZskykGz6HzRmgC4Ez2bBoCp4" />
</form>

-----------------------------

Then Submit the form with the AntiForgeryToken:

POST http://localhost/User/Favorite/Mark?url=156

__RequestVerificationToke...    WVXhVJJ3VNB8HrZQ6CZBPt35z2zvDjaHmlYWrnCvJoDUgeWMEGUGwm3clCD27vFAsxbs0upiRdVdo9Wsus Z7B6SU NQgV3iSYTUtE/EREWqT1Is/kwNZpdNf/3Pi7fD572pO89lTdYEjL0OlzmPJ5tmRQEUq/oMbuj0MnmPZskykGz6HzRmgC4Ez2bBoCp4

My question is simple. This is a good practice to get a AntiForgeryToken for an Ajax request? or is a bad idea?

I have this question because I don't know if this idea can make a bug hole to exploit on my site in this specific actions.

Thanks


Solution

  • Why don't you just POST a request to the server (using AJAX) when the user hits 'favorite' and use the AntiForgery token you already have in the page? Your approach is needlessly over-complicated.

    See Problems implementing ValidatingAntiForgeryToken attribute for Web API with MVC 4 RC and related links for how to get the token into your Ajax request.