Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between null_session and reset_session in Rails 4?

I'm currently working on a Rails application with a few other developers, and there are POSTs being made to the server via AJAX through Angular. On occasion, we've noticed a few InvalidAuthenticityToken exceptions come through our email logs, which has led to us wanting to take action.

Since this request is coming through Angular, my belief is that we are treating the server as an API, and we should be using protect_from_forgery with: :null_session. However, protect_from_forgery with: :reset_session seems to provide us with the same resolution.

I don't wish to blindly plug code in just because it's recommended, so I'd like to know the difference between these two forgery protection approaches. When would I use one over the other, and why would I prefer its usage?

like image 226
Makoto Avatar asked Jun 01 '15 20:06

Makoto


1 Answers

Based on my interpretation of the code, it seems that:

  • null_session should be used in API-style controllers, where you have no use for the session object. This sounds like the appropriate solution for your Angular app. The user's preexisting session (i.e. as set by other, traditional controllers) will remain intact. It is also the default behavior if you don't specify a with option to protect_from_forgery.
  • reset_session is for traditional controllers. When the CSRF check fails, it tells Rails to blow away the user's session and continue handling the request. This sounds like a "paranoid mode" where you want to log the user out of your app if there is any evidence of tampering in the request.

If your Rails app doesn't use sessions at all, then these are interchangeable.

However, if you do use sessions in some parts of your app but not others (i.e. a mix of traditional and API controllers), then null_session is probably what you should use. Otherwise, if you use reset_session, an API request made by the browser will cause users to be logged out of their browser session.

like image 159
Matt Brictson Avatar answered Nov 17 '22 11:11

Matt Brictson