0

I have a simple rails app with a single controller. I have a "before filter" for some of the methods of my controller, where I check if the user is logged in by looking at the session object:

@user = User.where(:id => session[:user_id]) if session[:user_id]

In a "login" method of my controller, I do:

session[:user_id] = user.id

Pretty usual stuff. If I access my app from a web browser (Chrome), everything works fine. However, when I use NSURLRequest from my iOS app to access my rails app, the server always creates a new session for each request. It never seems to be able to identify the existing session, even though the request is sending the cookie with the proper session ID in it. In fact, if I look at the "cookies" object in my rails app, I can see it contains the session ID. However, the session object is always empty! Not sure why the server is not able to retrieve the session. I'm using Passenger Phusion. Any suggestions?

DarezGhost
  • 59
  • 11
  • Are you sure the `cookies` object in the rails app contains *the* session ID and not just *a* session ID? If the app sends a request without one, the first thing the rails server will do is allocate a new session ID and set it in a cookie. So you will always see a session ID. The thing to verify is that it is not changing on each request. – aroth Oct 07 '12 at 02:23
  • the iOS's first request is to "login". This request is without any cookie. The server creates a new session and sends the ID back in a cookie. Then, the iOS's second request, it sends a cookie to the rails app with the session ID returned from the previous request. I did verify that it is EXACTLY the same ID that was returned by the server after the first request. However, the server just returns yet another session ID for the second request. – DarezGhost Oct 07 '12 at 02:31

1 Answers1

1

If you are POSTing to your login page, and the post does not include a CSRF token matching the token in the session, then Rails will fail the request and invalidate/reset the session as a security precaution.

To fix it, simply read the CSRF token out of the session and include it in your request, or turn off CSRF token checking, you can place skip_before_filter :verify_authenticity_token in your controller to skip the CSRF protection checks. Note that the latter approach does open potential security holes, so including the tokens and checking them is recommended if it is at all viable.

Chris Heald
  • 61,439
  • 10
  • 123
  • 137