Search code examples
c#asp.netwebformscsrf

Where to store CSRF token - ViewState or Session?


I've been looking into the CSRF vulnerability and how to fix it in .NET application.

Based on my research here is the pseudo algorithm I need to do:

  1. Check request for CSRF token in the request cookie, if it is not there, create one on the server.
  2. Once the token is created, add the token to the response cookie to send back to client. Client sends this CSRF token for all future request cookie.
  3. When server receives a request and it sees the CSRF cookie, the server validates against its stored CSRF token value.
  4. When it matches, then business as usual, if the values don't match then stop the request.

My question is in step #3, I'm using ASP .NET web form; I can store this CSRF token in either Session or a ViewState.

I don't want to use ViewState because all the pages in our application have to support EnableViewState="true". If not, the ViewState content is wiped out on each and every post-back call.

Can I use Session in this situation? Does it compromise the fix if I use Session instead of ViewState?


Solution

  • So you're going for the Synchronizer token pattern (STP) technique, using a single token per user session.

    There's no problem in using the ASP .NET session storage for saving CSRF tokens, based on the trivial assumption that the attacker has no access to it, this doesn't compromise your solution in any way. Nonetheless, as pointed out in Gabor Lengye's comment, using cookies to send the CSRF token to the server is flawed, embed the token in an HTML form instead, or use the Cookie-to-header token technique.

    That said, I suggest you take a look at the AntiForgery Class which has built-in token generation, HTML embedding and validation methods. Security wise it's never a good idea to implement your own solution, instead go for established, trusted solutions.

    Also make sure to use HTTPS to prevent your tokens from being hijacked in a Sniffing attack